Small discussion on JavaScript compatibility

Source: Internet
Author: User
Small discussion on JavaScript compatibility
 
Large, medium, and small
Hello, everyone. I am very happy to work with you to study the technical problems you will encounter when you do this web page. Many people say that Internet Explorer [Internet Explorer for short] is supported, and other browsers can ignore it! In fact, no matter from which statistics, ie's market share is only about 80%. In order to solve this problem, I had a long discussion with the PHP Group's colleagues. They also showed me their statistics: only 70% use IE!

I was surprised to hear that other browsers share so much. Why didn't I learn the differences between browsers during development? Therefore, I spent a lot of time organizing and summarizing these differences. Of course, it was impossible for me to understand these differences. That was what Wulin experts did. So I found some materials and made some tests, of course, this is also the basis of this article. Now, let's get started with code. I have summarized some scattered and common problems and shared them with you, hoping to help you.
First: onload

This code is extracted from the top ten common JavaScript Functions after the web page is loaded and executed. Of course there are other implementation methods, but this function is really clever. Efficiency is also a very useful function!
The following code is used:
//--------------------------------------------------------
Function addloadevent (func ){
VaR oldonload = Window. onload;
If (typeof window. onload! = 'Function '){
Window. onload = func;
}
Else {
Window. onload = function (){
Oldonload ();
Func ();
}
}
}
//--------------------------------------------------------
I don't want to explain this addloadevent in one sentence, which is very difficult for the experts to accept! Let's talk about its compatibility! See window. onload in the function. Why does the author not use document. Body. onload? That's because under Firefox [All hereinafter referred to as ff], document. Body. onload is undefined (undefined). Assigning a function to undefined does not cause anything or an error! This is a headache! Okay. Do you know the compatibility is amazing? So pay attention to the code later!
Second: Body
This body object is also a thing that troubles us. It is called that the object does not know, right? I am not a computer professional, and the terminology is really not clear!
The following code is used:
//--------------------------------------------------------
Function getpagescroll (){
VaR yscroll;
If (self. pageyoffset ){
Yscroll = self. pageyoffset;
}
// Explorer 6 strict
Else if (document.doc umentelement & document.doc umentelement. scrolltop ){
Yscroll = document.doc umentelement. scrolltop;
} Else if (document. Body) {// all other referers
Yscroll = Document. Body. scrolltop;
}
Arraypagescroll = new array ('', yscroll)
Return arraypagescroll;
}
//--------------------------------------------------------
This function is used to read the height of the browser scroll bar. This is an excerpt from lightbox. Read this code and see three judgments:
1. If (self. pageyoffset) Judges and processes ff;
2. if (document.doc umentelement & document.doc umentelement. scrolltop is the judgment of the webpage standard (XHTML 1.1 DTD). Here we should explain: When the XHTML 1.1 DTD file header is added, document. body. the value of scrolltop is often 0, which is hard to be noticed by debugging (I used to be confused for a long time, so I have passed on the experience here !);
3. We often use document. Body. scrolltop.
From these three judgments, we can imagine the strict thinking of the author! Of course, this is the commonality of programmers!

Third: attachevent/addeventlistener
There is a direct difference here, but too many direct causes programming troubles, which reminds people of the following: how many direct different functions are there? Where are their differences? After all, we have limited brain space. How can we remember this? But these must be remembered! It's okay. Common JS compatibility mentioned in this article can be used as a small manual for "home travel, portable!
The following code is used:
//--------------------------------------------------------
_ Observeandcache: function (element, name, observer, usecapture ){
If (! This. Observers) This. Observers = [];
If (element. addeventlistener ){
This. Observers. Push ([element, name, observer, usecapture]);
Element. addeventlistener (name, observer, usecapture );
} Else if (element. attachevent ){
This. Observers. Push ([element, name, observer, usecapture]);
Element. attachevent ('on' + name, observer );
}
}
//--------------------------------------------------------
Add events to an object. This is part of the class in the prototype of Sam Stephen son. The Code does not allow you to analyze the prototype slowly. JS file, which only indicates that obj can be used in IE and opera. attachevent (), but only obj. addeventlistener ().
Similar differences include:
Detachevent/removeeventlistener
Parentelement/parentnode
Insertadjacentelement/appendchild
Srcelement/Target
Onmousewheel/dommousescroll
Clienty/Pagey

Fourth: Object Reference
1. getelementbyid
See the following code:
<! -- 1 -->
<Input id = "T1"> <input type = "button"
Value = "Click me" onclick = "alert (t1.value)">
<! -- 2 -->
<Input id = "T1"> <input type = "button"
Value = "Click me" onclick = "alert (document. getelementbyid ('t1'). Value)">
Both of them obtain the value of the text box, but the latter is more compatible than the former! For ie, the ID of an HTML element can be directly used as a variable name in the script, but not in ff.
Getelementbyid is a very useful and common function, so we should try to use it when referencing an object!
2. var
See the following code:
//--------------------------------------------------------
Echo = function (STR ){
Document. Write (STR );
}
//--------------------------------------------------------
This function runs normally on IE, but an error is reported under ff, and VaR is added before ECHO, which is the purpose of var.
3. []
Document. Forms ("formname") is changed to document. Forms ["formname"] objective: to use () For many collection class objects in the existing code, ie can accept it, but FF cannot.
4. Frame reference
Ie can access the window object corresponding to the frame through ID or name, while MF can only access the window object corresponding to the frame through name.

Fifth: Script Execution
Let's perform a test separately. Ask IE and FF to run the following JS section of idea respectively:
//--------------------------------------------------------
O = {
Foo: function (){
Alert ("fly ");
}
};
With (o ){
Bar ();
Function bar (){
Alert ("fly ");
}
Foo ();
}
//--------------------------------------------------------
In ie, the above Code successfully outputs fly. FF reports the error: bar is not defined!
Of course, this is a small experiment. We can see that IE and FF support execution: IE Script pre-interpretation execution, FF script execution in sequence! This is something you must pay attention to when writing and designing JavaScript!

Sixth: XMLHTTPRequest object
See the following code
//--------------------------------------------------------
Function createrequest (){
If (typeof XMLHttpRequest! = "Undefined ")? {
Return new XMLHttpRequest ();
} Else if (typeof activexobject! = "Undefined "){
VaR xmlhttp_ver? = False;
VaR xmlhttp_vers = [
"Msxml2.xmlhttp. 5.0 ",
"Msxml2.xmlhttp. 4.0 ",
"Msxml2.xmlhttp. 3.0 ",
"Msxml2.xmlhttp ",
"Microsoft. XMLHTTP"
];
If (! Xmlhttp_ver ){
For (VAR I = 0; I <xmlhttp_vers.length; I ++ ){
Try {
New activexobject (xmlhttp_vers [I]);
Xmlhttp_ver = xmlhttp_vers [I];
Break;
} Catch (oerror ){;}
}
}
If (xmlhttp_ver ){
Return new activexobject (xmlhttp_ver );
} Else {
Throw new error ("cocould not create xml http request .");
}
} Else {
Throw new error ("your browser doesn't support an xml http request .");
}
}
//--------------------------------------------------------
The XMLHTTPRequest object is written by a brother of joy village. In IE, a new activexobject ("msxml2.xmlhttp") can be used to solve the problem, but here we have spent so many lines of code to solve the compatibility problem. The author of this function starts from the principle: xmlhttp_vers should be written from a higher version to a lower version. In this way, the object data is called by msxml2.xmlhttp of the highest version installed on your machine. It is very clever and effective to get the object!

Well, there are still many examples of JavaScript compatibility, so we cannot list them all. Here we will give a brief introduction, and more can only be understood in programming projects! Of course, this article only discusses the compatibility of JS, and the issue of CSS compatibility cannot be ignored! The best solution to compatibility is encapsulation! Next time, I have the opportunity to study CSS compatibility and JS encapsulation with you! This article, based on your own experience and the experience of online friends, is here. I don't know how everyone feels? Is there any benefit? If there is a little bit, my task will be completed!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.