JavaScript event loading and pre-loading _javascript techniques

Source: Internet
Author: User

Normally, window.onload is sufficient, and if you want to load multiple events, we can do the following:

Copy Code code as follows:

Window.onload = function () {
Func1 ();
Func2 ();
Func3 ();
More load events ....... ......
}

But if it's because of some special need, can't we just write together? If the current area is for the administrator, the background generated only when the user is an administrator, the page to generate this part, and this part of the use of some special scripts, the above methods on the rest of the dishes!
Copy Code code as follows:

Background code
<script type= "Text/javascript" >
Window.onload = function () {
Func1 ();
Func2 ();
Load the script used by ordinary users ...
}
</script>
<%# The following scripts are prepared for administrators%>
<% if @user. Role = = "Manager"%>
Window.onload = function () {
Func1 ();
Func2 ();
Load Secret script ...
}
<% End%>

The resulting page has two window.onload code blocks, and obviously the second one overrides the first. At this time, the turn to the Loadevent function appeared.
Copy Code code 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 solves the problem of covering each other perfectly, and uses the following:
Copy Code code as follows:

Loadevent (FUNC1);
Loadevent (FUNC2);
Loadevent (FUNC3);
More Load Events

But the real problem is always so surprising, and so tricky. I recently wanted to put all the functions in a closure to avoid naming conflicts, such as the famous $ Dom selector. Jquery,prototype,mootool all use it as the name of the selector, coexistence becomes a serious problem.
Copy Code code 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.$ = $;
})()

<textarea id="runcode41556"><!doctype html> <ptml dir= "ltr" lang= "ZH-CN" > <pead> <meta charset= "gb2312"/> <meta H ttp-equiv= "x-ua-compatible" content= "Ie=edge" > <title> event Loading in a closed environment </title> <script type= "text/ JavaScript > (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.$ = $; }) () Js.onready (function () {var $ = js.$; try{Alert ($ ("test"). InnerHTML); }catch (e) {alert (e); ) </script> </pead> <body> <p id= "test" >Test</p> </body> </ptml> </c0 ></textarea>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

However, there is a flaw in such a well-known function, that is, the newly loaded function is placed in the scope of the previous load function, the more the load function, the deeper the stack level, obviously the energy consumption is very large. However, such functions as onclick,onload,onmouseout, which are classified as DOM0 event models, benefit from a wide range of applications, but are checked for performance, Then, the DOM1.0 event model and the DOM2.0 event model are proposed, which is the combination of the original Microsoft event model and the original Netscape event model, both capturing and bubbling, and multiple binding multiple types of events without causing the latter to overwrite the former. So people always get the famous addevent function out, we use addevent to transform our event loading.
Copy Code code 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 a closed environment </title> <script type= "text/ JavaScript > (function () {if (!window). JS) {window[' js '] = {}} var addevent = function (obj, type, fn) {if (Obj.addeventlistener) Obj.addeventlistener (t Ype, 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.$ = $; }) () Js.onready (function () {Alert (js.$ ("test"). InnerHTML)},true); Js.onready (function () {alert ("dddddddddddddddd")},true); </script> </pead> <body> <p id= "test" >Test</p> </body> </ptml>
[Ctrl + A All SELECT Note: If the need to introduce external JS need to refresh to perform]

OK, no problem. The Onready function above has an optional parameter for whether the picture is to be loaded. We know that the JS engine will only start processing pictures and audio after the DOM tree is finished, but what if our page relies heavily on the script layout?! We want to make the page appear in general form as soon as possible, this use Domready. We improve it on the basis of the original.
Copy Code code 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.documentElement.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 browser with domcontentloaded, this is very much the current Dommousescroll Dom method, and FF is not the same, basically all non-IE kernel browser latest version support it. IE we can listen to the document. DocumentElement. DoScroll () to determine whether the DOM tree is complete, the principle of IE is only when the DOM tree is built to DoScroll. However, it is not perfect, it can not determine the content of the IFRAME in IE is finished loading. We continue to improve it.
Copy Code code 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.documentElement.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, with the use of closures made of namespaces, basic bulletproof. And it only pollutes a global variable "JS", can be comparable with Yui (laugh). But for general applications, we don't have to be so exhaustive. If we do not need to deal with the image, the page does not have an IFRAME, we can do the following miniature version out.
Copy Code code as follows:

(function () {
if (!window. JS) {
window[' JS '] = {}
}
var onready = function (loadevent) {
if (!+ "\v1") {
(function () {
try {
Document.documentElement.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.