JavaScript browser compatibility

Source: Internet
Author: User
Tags event listener html comment

JS <noscript> Tagsearly browsers were faced with a special problem: How to make the page degenerate smoothly when the browser does not support JavaScript. The ultimate solution to this problem is to create a <noscript> element that displays the alternative content in browsers that do not support JavaScript. This element can contain any HTML element that can appear in document <body> except for one by one <script> elements.

The content contained in the <noscript> element is displayed only in the following cases:
    • The browser does not support scripting;
    • The browser supports scripting, but the script is disabled.

If any of these conditions are met, the browser will display the contents of <noscript>. In other cases, the browser does not render the contents of the <noscript>.

Here's a simple example:
<HTML><HEAD><TIT1E>EXARNP1E html page</tit1e><script type= "Text/javascript" defer= " Defer "src=" example1. JS "></script><script type=" Text/javascript "defer=" defer "src=" example2. JS "></script>

This page will display a message to the user if the script is invalid, and in a script-enabled browser, the user will never see it one at a-although it is part of the page.

Note: JavaScript is supported in modern browsers, and the content of <noscript> is typically displayed when the user's browser disables scripting.

Deprecated syntax for embedded JS scripts

in the early introduction of the <script> element, this element is in conflict with the parsing rules of traditional HTML. Because of the special parsing rules that are applied to this element, the most typical of those browsers that do not support JavaScript one by one is mosaic-one by one, which can cause problems. Specifically, the browser gang that does not support JavaScript will output the contents of the <script> element directly to the page, thus destroying the layout and appearance of the page.

<script><!--function Sayhi () {alert ("hi!");--></script>


Netscape and Mosaic negotiated and proposed a solution that allows browsers that do not support <script> elements to hide embedded JavaScript code. The solution is to include the JavaScript code in an HTML comment, like this:
When you add HTML annotations to a script, browsers such as Mosaic ignore the contents of the <script> tag, and those browsers that support JavaScript must further confirm that they contain JavaScript that needs to be parsed when they encounter this situation Code.

Although the format of this annotated JavaScript code is recognized by all browsers, it can be interpreted correctly, but since all modern browsers already support JavaScript, there is no need to use this format anymore.

JS Event Compatibility Inquiry

The event is the user's action, for example: the user clicks the mouse, generates the OnClick event, presses the keyboard, generates the OnKeyDown event, changes the value of the input box, and produces the onchange event ...

The standard specifies that events are passed in as arguments to functions, such as:
<p id= "Demo" > Click I will get screen coordinates </p>
document.getElementById ("Demo"). Onclick=function (e)
{
alert (E.screenx);
}
when clicked on an element, a pop-up warning box appears with the mouse's horizontal axis on the screen. Here the function passed in the parameter e, is the event, the browser will be real-time tracking user behavior, such as E.screenx, E.screeny, E.offsetx, e.offsety ...

this practice in Firefox, Chrome, Safari and other follow the Web browser is not a problem, except in IE (temporarily limited to 8.0 versions, more than 8.0 version of the author has not tested) is not feasible, IE adopted a non-standard way, Instead of passing events as function arguments, events are used as the event property of the Window object: window.event, Window.event.screenX ...

Therefore, we should be in the code to take care of IE, to do the event compatibility.

Here is a simple example of compatibility with the author, which does not judge the browser and uses only a small trick.
<p id= "Demo" > Click I will get screen coordinates </p>
document.getElementById ("Demo"). Onclick=function (e)
{
var e=e| | event;
alert (E.screenx);
}
Note that you do not e=e| var | Event Written as Var e=event| | E , this will prompt the error in Firefox, Firefox cannot process a variable event that does not declare an unassigned value.

Here you may have doubts, why is var e=e| | Event , why yes or arithmetic (| | ), so the result can only be e=true or e=false?

I'm telling you, in most programming languages, or operations (| | Returns not just true or false, but instead returns the value of the first variable that is not false . For example:
var a=5| |  6; A=5
var b=0| |  5; B=5
var c=false| | "  Www.itxueyuan.com "; C= "Www.itxueyuan.com"
var e=e| |  Event E for user Events

Well, these examples, I believe we must understand that the above on the case of the clever handling of the event, it will be solved.

It Academy reminds us that when dealing with browser compatibility issues, try not to judge the browser, that will be a risk for backward compatibility, perhaps an upgrade version began to follow the world standard, we wrote before the code in this version will produce errors, not expected results.

For example, an upgraded version of IE supports passing events as function arguments, discarding the properties of the event as a window, which is exactly what our code looks like:
if ( (/ie/i). Test (Navigator.useragent) )
document.getElementById ("Demo"). Onclick=function ()
{ the difference between Javascript AddEventListener and Attachevent
alert (Window.event.screenX);
    }
Else
document.getElementById ("Demo"). Onclick=function (e)
    {
alert (E.screenx);
    }
then running on the upgraded Internet Explorer will create an error.

Finally, comb the idea, and then repeat the above code again.
<p id= "Demo" > Click I will get screen coordinates </p>
document.getElementById ("Demo"). Onclick=function (e)
{
var e=e| | event;
alert (E.screenx);
} Browser kernelto figure out what the browser kernel is, you should first understand the browser's composition. In short, the browser can be divided into two parts, shell+ kernel. There are relatively many kinds of shell, and the kernel is relatively small. The shell refers to the browser's shell: menus, toolbars, and so on. The main is to provide user interface operation, parameter set landlord and so on. It is called the kernel to implement various functions. The kernel is the core of the browser. The kernel is a program or module that displays content based on markup language. There are also some browsers that do not differentiate between shells and cores. The gecko of the shell and the core is clearly separated from Mozilla. The current mainstream browser has IE6/7/8, Mozilla, FireFox, Opera, Safari, Chrome, Netscape and so on. What is the browser kernel

the browser kernel can be divided into two parts: the rendering engine (layout engineer or rendering engine) and the JS engine. It is responsible for acquiring the content of the Web page (HTML, XML, images, etc.), organizing the message (such as adding CSS, etc.), and calculating how the page will be displayed, and then outputting it to the display or printer. The browser's kernel is different from the syntax of the Web page, so the effect of rendering is not the same. JS engine is to parse JavaScript language, execute JavaScript language to achieve the dynamic effect of Web page. The first rendering engine and the JS engine are not clearly distinguished, and then the JS engine becomes more independent, the kernel tends to refer only to the rendering engine. There is a Web page standard planning team produced an acid to test engine compatibility and performance. There are many types of kernels, such as the non-commercial free kernel with no one to use, there may be more than 10 kinds, but the common browser kernel can be divided into four kinds: Trident, Gecko, Presto, Webkit.


Rendering engine Trident, also known as MSHTML, is Microsoft's development of the rendering engine (including JavaScript engine JScript), many browsers now use this engine, such as Ie,maxthon,tt,the world,360, Sogou Browser, Maxthon (the latest version has not been used), etc. Gecko is a C + + developed, Open source rendering engine that includes SpiderMonkey (Rhino). The main users are Firefox,netscape6 and above, Mozillasuite/seamonkey and so on.
WebKit was developed by Apple based on Khtml. He consists of WebCore and JavaScriptCore (SQUIRRELFISH,V8) two engines. The main users are safari,chrome. Presto was started by Opera Software and was used by opera's rendering engine. Macromedia Dreamweaver (MX version and above) and Adobe Creative Suite 2 also use the Presto kernel. The main users are Opera7 and above. JS Engineoriginally designed by Netscape's Brendan Eich, JavaScript is a dynamic, weakly-typed, prototype-based language with landlord support classes within it. Based on it, the ECMAScript standard is developed. His origins are not, as described in the JavaScript Advanced programming book, Brendan Eich's own invention. (Refer to Aimingoo's textual research article) JavaScript must also contain DOM and BOM in the implementation of the browser. Web browsers typically use public APIs to create host objects that are responsible for reflecting DOM objects into JavaScript.

JavaScript handling of mouse wheel events

The web does not regulate the mouse wheel events, the browser vendors encapsulate different implementation methods, event attributes are not the same, known as the most standard Firefox, with a private implementation Dommousescroll. However, other browsers are implemented with OnMouseWheel, so it is not very difficult to do compatibility processing.

Browser Implementation method Event Properties Scroll up Scroll down
FireFox Dommousescroll Detail -3 3
Non-Firefox OnMouseWheel Wheeldelta 120 -120

The so-called event attribute is the change of a particular variable when the wheel scrolls. The variable does not require user-defined and is present as an attribute of the event.

    • For Firefox, this variable is detail: Scroll up, detail=-3, scroll down, detail=3.
    • For non-Firefox, this variable is wheeldelta: Scroll up, wheeldelta=120, scroll down, wheeldelta=-120.


In addition, there is a point to note.

    • Under Firefox, Dommousescroll must be bound by AddEventListener, such as:
      Element.addeventlistener ("Dommousescroll", Fun,false)
    • In the non-Firefox, there is no limit, in addition to the above method, you can also use the following code:
      Element.onmousewheel=function () {}


I finally summed up a piece of compatible code for everyone to use.

    • compatibility with implementation methods:
      /**
      * Register Wheel Event function
      * @param event object registered by Ele
      * @param Fun Register event function
      */
      function MouseWheel (ele,fun)
      {
      (/firefox/i). Test (Navigator.useragent) ele.addeventlistener ("Dommousescroll", Fun,false): Ele.onmousewheel=fun;
      }
    • for compatibility with event properties:
      /**
      * Compatible handling of wheel event properties, regardless of browser, final unification: mouse wheel scroll up detail=-3, scroll down detail=3
      */
      function Fun (e)
      {
      var e=e| | Event
      var detail=e.detail| | parseint (-E.WHEELDELTA/40);
      /* Add code */
      }

Example: The mouse scrolls on the picture, the picture zooms in or shrinks.

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/>
<title> effects: Scroll the mouse over the picture, zoom in or out of the image </title>
<body>

<br/><br/><br/><br/>

<script language= "JavaScript" type= "Text/javascript" >
function Fun (e)
{
var e=e| | Event
var detail=e.detail| | parseint (-E.WHEELDELTA/40);
This.setattribute ("height", this.offsetheight+4*detail);
}

function MouseWheel (ele,fun)
{
(/firefox/i). Test (Navigator.useragent) ele.addeventlistener ("Dommousescroll", Fun,false): Ele.onmousewheel=fun;
}

For (Var imgs=document.getelementsbytagname ("img"), len=imgs.length,i=0;i<len;i++)
{
MouseWheel (Imgs[i],fun)
}
</script>
</body>
The difference between Javascript AddEventListener and attachevent

first, JavaScript has 3 ways of binding event snooping:

    1. <div onclick= "alert (" event binding succeeded!) ")" > Event binding demo</div>
    2. <div id= "Div1" > Event bindings demo</div>
      document.getElementById ("Div1"). Onclick=function () {
      Alert ("Event binding succeeded!") ");
      }
    3. <div id= "Div1" > Event bindings demo</div>
      function Fun () {
      Alert ("Event binding succeeded!") ");
      }
      document.getElementById ("Div1"). AddEventListener ("click", Fun,false);

AddEventListener and Attachevent are the third methods of binding event monitoring, and the differences are as follows.

I. Compatibility issues with AddEventListener and attachevent
    • AddEventListener is a code-compliant event binding method that FireFox, Chrome, and Safari use to bind events.
    • Attachevent is IE private, does not conform to the specifications, and under IE, can only use it to bind events, AddEventListener is invalid.

Therefore, compatibility issues must be addressed in order to bind events.

Ii. grammatical rules of AddEventListener and attachevent
  • AddEventListener a total of 3 parameters, as follows:
    Element.addeventlistener (type,listener,usecapture);
    Parameters parameter Description
    Element The object to bind the event to, and the HTML node.
    Type Event name, notice the "on" in front of the event, such as "onclick" to write "click", "onmouseover" to write "MouseOver".
    Listener To bind the event listener function, note that only the function name is written, not with parentheses.
    Usercapture The event listener can only be true and False:true, using capture (Capture) mode, false, bubbling (bubbling) mode. If no special requirements, it is generally false.
    Here it is necessary to say the difference between capture mode and bubbling mode.

    , there are two levels of DIV elements, and all of them have a click event, and generally, if I click on the inner blue element, it will not only trigger the Click event of the blue element, but it will also trigger the Click event of the red element. The Usecapture parameter is the order in which two click events are controlled at this time. If it is false, then it will use the bubbling (bubbling) mode, which is the process from the inside out, so the click event of the blue element is executed before the Click event of the red element is executed, and if true, the capture mode, and bubbling (bubbling The inverse of the pattern is the click event of the blue element, which executes the Red element's Click event First, by the outside and inside.
    If the elements of different layers use different usecapture, the event that is set to capture (capture) mode is first searched from the outermost element to the target element, and the target element executes the event of the target element, and then seeks out the original path to look out for events set to bubbling (bubbling) mode.
  • Attachevent a total of 2 parameters, as follows:
    Element.attachevent (Type,listener);
    Parameters parameter Description
    Element The object to bind the event to, and the HTML node.
    Type The event name, note plus the "on" in front of the event, such as "onclick" and "onmouseover", which is the difference from AddEventListener.
    Listener To bind the event listener function, note that only the function name is written, not with parentheses.
Third, code compatibility processing

function Regevent (ele, Event_Name, fun)
{
if (window.attachevent)
ele.attachevent (event_name, fun); IE browser
Else
    {
event_name = Event_name.replace (/^on/, ""); If on starts, remove on, such as Onclick->click
Ele.addeventlistener (Event_Name, fun, false); Non-IE browser
    }
}

Note that the IE browser should not be judged in this way:
(/msie/i). Test (Navigator.useragent)
Although this method is easy to understand, but there is a big hidden danger, is that the browser after the upgrade to support the standard, and did not do backward compatibility, in this case there will be error prompts, program crashes, increased maintenance costs.

JavaScript browser compatibility

Related Article

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.