Javascript event loading and pre-loading

Source: Internet
Author: User

Generally, window. onload is enough. To load multiple events, we can use the following method:
Copy codeThe Code is as follows:
Window. onload = function (){
Func1 ();
Func2 ();
Func3 ();
// Load more events ..................
}

But can't we write together because of a special need? For example, the current region is for the Administrator. This part is generated only when the user is an administrator in the background, and some special scripts are used in this part. The above method will take a break!
Copy codeThe Code is as follows:
// Background code
<Script type = "text/javascript">
Window. onload = function (){
Func1 ();
Func2 ();
// Load the script used by common users ......
}
</Script>
<% # The following script is prepared for the Administrator. %>
<% If @ user. role = "manager" %>
Window. onload = function (){
Func1 ();
Func2 ();
// Load the confidential script ......
}
<% End %>

In this case, the generated page has two window. onload code blocks. Obviously, the second one overwrites the first one. At this time, it is the turn of the loadEvent function to appear.
Copy codeThe Code is as follows:
Var loadEvent = function (fn ){
Var oldonload = window. onload;
If (typeof window. onload! = 'Function '){
Window. onload = fn;
} Else {
Window. onload = function (){
Oldonload ();
Fn ();
}
}
}

It perfectly solves the problem of mutual coverage. Its usage is as follows:
Copy codeThe Code is as follows:
LoadEvent (func1 );
LoadEvent (func2 );
LoadEvent (func3 );
// More loading events

But the real problems are always so surprising, and they are also so embarrassing. Recently I want to put all functions in a closure to avoid naming conflicts, such as the famous $ DOM selector. JQuery, Prototype, and mootool use it as the selector name. Coexistence is a serious problem.
Copy codeThe Code is as follows:
(Function (){
If (! Window. JS ){
Window ['js'] = {}
}
Var onReady = function (fn ){
Var oldonload = window. onload;
If (typeof window. onload! = 'Function '){
Window. onload = fn;
} Else {
Window. onload = function (){
Oldonload ();
Fn ();
}
}
}
JS. onReady = onReady;
Var $ = function (id ){
Return document. getElementById (id );
}
JS. $ =$;
})()

<! Doctype html> <ptml dir = "ltr" lang = "zh-CN"> <pead> <meta charset = "gb2312"/> <meta http-equiv = "X-UA -Compatible "content =" IE = Edge "> <title> event loading in the closure environment </title> </pead> <body> <p id =" test "> Test </p> </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
However, this well-known function has another drawback: The newly loaded function is placed in the scope of the previous function to be loaded. The more loaded functions, the deeper the stack level, obviously, the energy consumption is very high. However, for functions such as onclick, onload, and onmouseout, W3C places them in the DOM0 event model. The advantage is that the function has a wide range of applicability, but it is dependent on its performance, therefore, the DOM1.0 event model and DOM2.0 event model were proposed. DOM2 is a combination of the original Microsoft Event model and the original event model of the Web site, which can capture and bubble up, in addition, binding multiple types of events does not cause the latter to overwrite the former. So people always come up with the famous addEvent function. We use addEvent to transform our event loading.
Copy codeThe Code is as follows:
(Function (){
If (! Window. JS ){
Window ['js'] = {}
}
Var addEvent = function (obj, type, fn ){
If (obj. addEventListener)
Obj. addEventListener (type, fn, false );
Else if (obj. attachEvent ){
Obj ["e" + type + fn] = fn;
Obj. attachEvent ("on" + type, function (){
Obj ["e" + type + fn] ();
});
}
};
Var onReady = function (loadEvent, waitForImages ){
If (waitForImages ){
Return addEvent (window, 'load', loadEvent );
}
}
JS. onReady = onReady;
Var $ = function (id ){
Return document. getElementById (id );
}
JS. $ =$;
})()

<! Doctype html> <ptml dir = "ltr" lang = "zh-CN"> <pead> <meta charset = "gb2312"/> <meta http-equiv = "X-UA -Compatible "content =" IE = Edge "> <title> event loading in the closure environment </title> </pead> <body> <p id =" test "> Test </p> </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
OK. No problem. The onReady function above has an optional parameter to determine whether to wait for image loading. We know that the JS engine will start to process images, audios, and other things after the DOM tree is completed. But what if our page is heavily dependent on script layout ?! We want to display the general form of the page as soon as possible, which uses domReady. We improved it on the original basis.
Copy codeThe Code is as follows:
(Function (){
If (! Window. JS ){
Window ['js'] = {}
}
Var addEvent = function (obj, type, fn ){
If (obj. addEventListener)
Obj. addEventListener (type, fn, false );
Else if (obj. attachEvent ){
Obj ["e" + type + fn] = fn;
Obj. attachEvent ("on" + type, function (){
Obj ["e" + type + fn] ();
});
}
};
Var onReady = function (loadEvent, waitForImages ){
If (waitForImages ){
Return addEvent (window, 'load', loadEvent );
}
Var init = function (){
If (arguments. callee. done) return;
Arguments. callee. done = true;
LoadEvent. apply (document, arguments );
};
If (! + "\ V1 "){
(Function (){
Try {
Document.doc umentElement. doScroll ("left ");
} Catch (e ){
SetTimeout (arguments. callee, 0 );
Return;
}
Init ();
})();
} Else {
Document. addEventListener ("DOMContentLoaded", function (){
Document. removeEventListener ("DOMContentLoaded", arguments. callee, false );
Init ();
}, False );
}
Return true;
}
JS. onReady = onReady;
Var $ = function (id ){
Return document. getElementById (id );
}
JS. $ =$;
})()

Dom standard browsers use DOMContentLoaded, which is a very common W3C DOM method. Unlike FF's DOMMouseScroll, the latest version of all non-IE kernels supports it. In IE, we can determine whether the DOM tree is complete by listening to document. documentElement. doScroll (). The principle is that in IE, doScroll can only be performed after the DOM tree is built. But it is not perfect. It cannot determine whether the iframe content has been loaded in IE. We continue to improve it.
Copy codeThe Code is as follows:
(Function (){
If (! Window. JS ){
Window ['js'] = {}
}
Var addEvent = function (obj, type, fn ){
If (obj. addEventListener)
Obj. addEventListener (type, fn, false );
Else if (obj. attachEvent ){
Obj ["e" + type + fn] = fn;
Obj. attachEvent ("on" + type, function (){
Obj ["e" + type + fn] ();
});
}
};
Var onReady = function (loadEvent, waitForImages ){
If (waitForImages ){
Return addEvent (window, 'load', loadEvent );
}
Var init = function (){
If (arguments. callee. done) return;
Arguments. callee. done = true;
LoadEvent. apply (document, arguments );
};
If (! + "\ V1 "){
If (window. self = window. top ){
(Function (){
Try {
Document.doc umentElement. doScroll ("left ");
} Catch (e ){
SetTimeout (arguments. callee, 0 );
Return;
}
Init ();
})();
} Else {
Document. attachEvent ("onreadystatechange", function (){
If (document. readyState = "complete "){
Document. detachEvent ("onreadystatechange", arguments. callee );
Init ();
}
});
}
} Else {
Document. addEventListener ("DOMContentLoaded", function (){
Document. removeEventListener ("DOMContentLoaded", arguments. callee, false );
Init ();
}, False );
}
Return true;
}
JS. onReady = onReady;
Var $ = function (id ){
Return document. getElementById (id );
}
JS. $ =$;
})()

We are simply re-implementing jquery's $ (document). ready (function (){})! It is very powerful and uses closures to create namespaces. In addition, it only contaminated a global variable "JS", which is comparable to YUI (Laugh ). However, for general applications, we do not need to be so comprehensive. If we do not need to process images, and there is no iframe on the page, we can make the following thumbnail.
Copy codeThe Code is as follows:
(Function (){
If (! Window. JS ){
Window ['js'] = {}
}
Var onReady = function (loadEvent ){
If (! + "\ V1 "){
(Function (){
Try {
Document.doc umentElement. doScroll ("left ");
} Catch (e ){
SetTimeout (arguments. callee, 0 );
Return;
}
LoadEvent ();
})();
} Else {
Document. addEventListener ("DOMContentLoaded", loadEvent, false );
}
}
JS. onReady = onReady;
Var $ = function (id ){
Return document. getElementById (id );
}
JS. $ =$;
})()

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.