In-depth understanding of JavaScript encapsulation domcontentloaded events

Source: Internet
Author: User
Tags event listener browser cache

Recently in writing a JavaScript framework, just put domcontentloaded events packaged, slightly small excitement, the development process encountered in the principles and compatibility issues to make a note, save the forgotten everywhere looking.

When we were writing the JS code, The Window.onload event is generally added, primarily to allow the DOM elements to be picked up after the DOM is loaded, but Window.load waits until the DOM is loaded , script, CSS, finally loading the picture or even all the resources in the IFRAME will be triggered, many times the picture of the Web page more large, to wait for the final picture this time-consuming big load after the execution JS obviously some too late, many times will affect the user experience.

Many JS frameworks have a document.ready function, like jquery's $ (document). Ready () method, you can execute the JS code as soon as the DOM is loaded, so that the picture is loaded from a slowly.

At the heart of Document.ready is the domcontentloaded event, where Firefox, Chrome, Opera, Safari, ie9+ can all use AddEventListener (' domcontentloaded ', Fn,false) for event binding, IE6~8 does not support domcontentloaded events, so compatibility is handled for ie6~8.

The data said that Ie6~8 can use the Document.onreadystatechange event listener Document.readystate State is equal to complete to determine whether the DOM is loaded, if the page is embedded with an IFRAME, ie6~ A 8 document.readystate will wait until all the resources in the IFRAME have been loaded before it becomes complete, when the IFRAME becomes a time-consuming large. However, after testing, even if there is no iframe in the page, when readystate equals complete, the OnLoad event is actually triggered instead of the domcontentloaded event, which is surprising.

Fortunately, IE has a unique doscroll method, when the page DOM is not loaded complete, call the DoScroll method, will be error, in turn, as long as the interval call doscroll until no error, it means that the page Dom loading is complete, This method works regardless of whether the contents of the picture and the IFrame are loaded.

If there are multiple JS files bound to the Document.ready event, in order to prevent the browser from repeating the binding, while the orderly execution, you can introduce an event queuing mechanism to solve.

The above is the principle and compatibility of the Document.ready event, the following example code, in order to facilitate the understanding of the implementation process, the use of the pattern of function encapsulation, the execution process is written in the comments, if there is a wrong place to welcome advice.

Save Domready Event Queue eventqueue = []; Determine if the DOM is loaded IsReady = false; Determine if Domready is bound isbind = false; /* Execute Domready () * www.111cn.net * @param {function} * @execute press event handlers into the event queue and bind domcontentloaded * If DOM loading is complete,    Execute immediately * @caller */function domready = function (fn) {if (IsReady) {fn.call (window);    } else{Eventqueue.push (FN);     }; Bindready ();}; /*domready Event Bindings * * @param null * @execute modern browsers bind domcontentloaded through Addevlistener, including ie9+ ie6-8 judging by the DoScroll    M is loaded complete * @caller domready () */function bindready = function () {if (isReady) return;    if (Isbind) return;     Isbind = true;    if (Window.addeventlistener) {document.addeventlistener (' domcontentloaded ', execfn,false);    } else if (window.attachevent) {doscroll (); };}; Www.111Cn.net/*doscroll Judge if the DOM of IE6-8 is loaded complete * * @param null * @execute DoScroll determine if the DOM is loaded complete * @caller bindready () */functi On doscroll = function () {try{-Document.documentElement.doScroll (' left ');    } catch (Error) {return setTimeout (doscroll,20);    }; EXECFN ();}; /* Execute Event Queue * * @param null * @execute event handlers in the Loop execution queue * @caller bindready () */function EXECFN = function () {if (!isread        Y) {IsReady = true;        for (var i = 0; i < eventqueue.length; i++) {eventqueue[i].call (window);        };    EventQueue = []; };}; JS file 1domReady (function () {...});  /js file 2domReady (function () {...});

  

/Note that if you are loading JS asynchronously, do not bind the Domready method, otherwise the function will not execute,
Because the domcontentloaded has been triggered before the asynchronous loading of JS download, the AddEventListener execution has not been monitored.
Test page: Both loaded with two large pictures, onload needs to load the picture to execute js,domcontentloaded just wait until the DOM is loaded to execute JS. You can open Firebug to view the loading process, and remember to clean up the browser cache before each test.

onload example

<! DOCTYPE html>

Domcontentloaded Example

<! DOCTYPE html>

  

In-depth understanding of JavaScript encapsulation domcontentloaded events

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.