Deep understanding of JavaScript encapsulation domcontentloaded events

Source: Internet
Author: User
Tags bind xmlns browser cache

When we write the JS code, The Window.onload event is typically added to select a DOM element to use, such as Getelementbyid,getelementsbytagname, after the DOM finishes loading, but Window.load waits until the DOM is loaded , scripts, CSS, the final load of the picture or even all the resources in the IFRAME will trigger, many times the picture of the page more large, to wait for the final picture this time-consuming big load before the implementation of JS is obviously some too late, many times will affect the user experience.

Many JS frameworks have a document.ready function, such as jquery's $ (document). Ready () method, can execute the JS code immediately after the DOM loading, lets the picture from slowly load.

Document.ready's core is the domcontentloaded event, Firefox, Chrome, Opera, Safari, ie9+ can all use AddEventListener (' domcontentloaded ', Fn,false) for event binding, and Ie6~8 does not support domcontentloaded events, so do compatibility handling for ie6~8.

The data says ie6~8 can use the Document.onreadystatechange event to listen document.readystate State is equal to complete to determine whether the DOM is loaded, if the page is embedded with IFRAME, ie6~ 8 of the document.readystate will wait until all the resources in the IFRAME load will become complete, at this time the IFRAME became a time-consuming large. But after testing, even if the page does not have an IFRAME, when readystate equals complete, the actual trigger is the OnLoad event rather than the Domcontentloaded event, to this point expressed surprise.

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

If more than one JS file is bound to the Document.ready event, in order to prevent the browser from repeating the binding and executing sequentially, an event queuing mechanism can be introduced to resolve it.

The above is the principle of the Document.ready event and compatibility issues, the following piece of example code, in order to facilitate the understanding of the implementation process, the use of function encapsulation mode, the implementation process are written in the comments, if there are irregularities welcome advice.

The code is as follows Copy Code
To save Domready event queues
EventQueue = [];

To determine if the DOM is finished loading
IsReady = false;

To determine whether Domready is bound
Isbind = false;

/* Execute Domready ()
* Www.111cn.net
* @param {function}
* @execute press event handlers into the event queue and bind domcontentloaded
* If the DOM load 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 via Addevlistener, including ie9+
Ie6-8 judge whether the DOM is loaded by DoScroll
* @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 to determine whether the DOM of the ie6-8 is loaded complete
*
* @param null
* @execute DoScroll to determine whether the DOM is finished loading
* @caller Bindready ()
*/
function DoScroll = function () {
try{
Document.documentElement.doScroll (' left ');
}
catch (Error) {
return settimeout (doscroll,20);
};
EXECFN ();
};

/* Execute event queue
*
* @param null
* @execute loop execution of event handlers in queues
* @caller Bindready ()
*/
function EXECFN = function () {
if (!isready) {
IsReady = true;
for (var i = 0; i < eventqueue.length; i++) {
Eventqueue[i].call (window);
};
EventQueue = [];
};
};

JS file 1
Domready (function () {
...
});
JS File 2
Domready (function () {
...
});

Note that if you are loading JS asynchronously, do not bind the Domready method, otherwise the function will not execute,
Since the asynchronous loading of JS download before the domcontentloaded has been triggered, addeventlistener execution has not been listening to the
Test page: are loaded with two large pictures, onload needs to load the picture to perform 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 the browser cache before each test.

onload example

The code is as follows Copy Code

<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>onload</title>
<style type= "Text/css" >
. div{width:200px;height:200px;background:red;}
Body{background:url (' bg.jpg ') no-repeat 0 0;}
</style> www.111cn.net
<!--script type= "Text/javascript" >
function Loadscript (URL) {
var head=document.getelementsbytagname (' head ') [0];
var s=document.createelement (' script ');
S.type= ' Text/javascript ';
S.src=url;
S.async=false;
Head.appendchild (s);
}

Loadscript (' go.js ');
Loadscript (' onload2.js ');
</script-->

<script type= "Text/javascript" src= "Go.js" ></script>
<script type= "Text/javascript" >
Window.onload=function () {
$ ('. Div '). MouseHover (function () {
$ (this). CSS (' background ', ' green ');
},function () {
$ (this). CSS (' background ', ' red ');
});
};
</script>

<body>
<div class= "div" > only wait until the picture is loaded, the mouse moved to my body will change color. <br/><br/><br/><br/><br/> (because the frame used does not support IE6, please use ie8+ test) </div>


</body>

domcontentloaded Example

The code is as follows Copy Code

<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title>DOMContentLoaded</title>
<style type= "Text/css" >
. div{width:200px;height:200px;background:red;}
Body{background:url (' bg.jpg ') no-repeat 0 0;}
</style>
<!--script type= "Text/javascript" >
function Loadscript (URL) {
var head=document.getelementsbytagname (' head ') [0];
var s=document.createelement (' script ');
S.type= ' Text/javascript ';
S.src=url;
S.async=false;
Head.appendchild (s);
}

Loadscript (' go.js ');
Loadscript (' onload2.js ');
</script-->

<script type= "Text/javascript" src= "Go.js" ></script>
<script type= "Text/javascript" >
$ (function () {
$ ('. Div '). MouseHover (function () {
$ (this). CSS (' background ', ' green ');
},function () {
$ (this). CSS (' background ', ' red ');
});
})
</script>

<body>
<div class= "div" > before the picture has been loaded, move the mouse to my body will change color oh .<br/><br/><br/><br/><br/> (Please use ie8+ test because the framework does not support IE6) </div>


</body>

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.