By Tony Ross (Program Manager)
Original article: Same Markup: Writing Cross-Browser Code
Translation: Once (csser.com)
Basic Principles
- Recommendation
- Function Test: Before using a function, check whether the browser supports it.
- Behavior detection: test known issues before application
- Not recommended
- Detect a specified Browser: changes page Behavior Based on the uniqueness of the browser
- Hypothetical unrelated functions: apply different functions based on the detection of one function
The principles listed above are important because most of today's pages are mixed with codes suitable for different browsers. These mixed codes are used to determine under which programs to run to suit different browsers, the most basic is script judgment, which usually looks like the following
If (condition ){
// Main code: csser.com
} Else {
// Backup code
}
The condition used in the above Code is not based on a given function in many cases, but on the browser used by the user. This may cause a problem: the standby code is executed based on the specified browser, thus limiting the adaptability of the webpage. The final result is that the page function will be affected once a new browser is released. At the same time, even if the new version of the browser adds new features, the code will continue with the old method. The following example illustrates this problem:
Event registration example (implemented based on browser Detection: not recommended)
You can easily test the effect of the following code. The sample code switches the event model by detecting the browser (poor practice.
// Event processing example function
Function f1 () {document. write ("addEventListener was used by csser.com ");}
Function f2 () {document. write ("attachEvent was used by csser.com ");}
// Not recommended: test the specified Browser
If (navigator. userAgent. indexOf ("MSIE") =-1 ){
Window. addEventListener ("load", f1, false );
} Else {
Window. attachEvent ("onload", f2 );
}
Result: The output in IE9 is attachEvent was used by csser.com. Obviously, even if IE9 already supports addEventListener, it will not be used
Event registration example (implementation based on function Detection: recommended)
The following code detects the switching event model through the function. Unlike the IE browser, it checks whether the addEventListener function is available. This code is not only available in ancient browsers that do not support addEventListener, more importantly, the browser can be used as long as it supports the addEventListener function.
// Event processing example function
Function f1 () {document. write ("addEventListener was used by csser.com ");}
Function f2 () {document. write ("attachEvent was used by csser.com ");}
// Recommended: Function Test
If (window. addEventListener ){
Window. addEventListener ("load", f1, false );
} Else if (window. attachEvent ){
Window. attachEvent ("onload", f2 );
}
To make suitable code run in a suitable browser, this is why function testing is increasingly used in web pages and frameworks. Function Testing allows smooth execution of cross-browser code without the need to fully understand the specific capabilities of different versions of different browsers. JQuery is a Javascript framework that relies almost entirely on function testing. In fact, the jQuery. support documentation details how to use function testing on your website.
Behavior detection (jQuery's getElementById example: recommended)
In addition to direct function testing, jQuery also uses behavior testing. It runs a piece of code with known issues to determine whether a work und is needed. The following is a modified snippet taken from the jQuery source code. It is used to test whether getElementById returns elements with the same name. This is a Bug in the old IE browser and IE8 has been fixed.
// Dynamically create a hyperlink element containing the name feature and place it in the dynamically created div Element
// In the document, the name value of this a element is unique.
Var form = document. createElement ("div "),
Id = "script" + (new Date). getTime ();
Form. innerHTML = "<a name = '" + id + "'/> ";
// Insert the created div element into the front-end of the page document
Var root = document.doc umentElement;
Root. insertBefore (form, root. firstChild );
// Pass in a unique id value through getElementById. If a matched element exists, the element with the name value is returned.
If (document. getElementById (id )){
//... Code...
// Code used for testing
Document. write ("getElementById workaround was used by csser.com ");
}
// Code used for testing
Else document. write ("No workaround was used by csser.com ");
Root. removeChild (form );
Hypothetical unrelated functions (practical: Poor)
The last thing I need to talk about is to speculate on unrelated functions, first go to the code, and then look at the results in different IE version browsers:
// Try-catch Block is used to capture execution errors in IE8.
Try {
Function fn () {alert ("www.csser.com ");}
If (window. postMessage ){
Window. addEventListener ("message", fn, false );
// Sample code
Document. write ("Message event registration successful ");
} Else {
// Code when postMessage is unavailable
// Sample code
Document. write ("postMessage not supported ");
}
} Catch (e ){
Document. write ("Message event registration failed ");
}
The execution results of the Code in the previous example under the IE7-9 are:
IE7: postMessage is not supported
IE8: Message event registration failed
IE9: Message event registration successful
The error in this example is that the writer thinks that the browser supports addEventListener when postMessage is supported. However, the postMessage function is supported in IE8, but addEventListener is added only from IE9. The correct fix code is as follows:
Function fn () {alert ("www.csser.com ");}
If (window. postMessage ){
If (window. addEventListener ){
Window. addEventListener ("message", fn, false );
} Else if (window. attachEvent ){
Window. attachEvent ("onmessage", fn );
}
// Sample code
Document. write ("Message event registration successful ");
} Else {
// Code when postMessage is unavailable
// Sample code
Document. write ("postMessage not supported ");
}