Simulate the ready method in jQuery and implement loading css as needed. js instance code _ jquery-js tutorial

Source: Internet
Author: User
This article describes how to simulate the ready method in jQuery and how to load css and js instance code as needed. If you need it, refer to it. 1. Implementation of ready Functions
I often use the ready method in the jQuery class library or other class libraries. Sometimes I think about how they are implemented. But I have read the source code in jQuery, and there are many modules involved (the level is limited) the code is hard to understand. I have combined some books and summarized them.
Let's talk about the implementation of the ready function:
The variable ready is assigned a value through an expression, and the right side is an self-executed anonymous function. In this anonymous function, the handler function is first bound to the events of Each browser, assign a value to isReady (determined by the asynchronous event handler), and return a passing parameter closure. In the closure, the isReady value is mainly used to perform the operation, if the dom structure is ready (isReady = true), execute the callback. Otherwise, add the callback to the queue (funs) to be executed. When the event processing program is executed, cyclically traverse the queue (funs) and execute the functions in the queue in sequence. After the functions in the queue are executed, you also need to clear the queue (funs = null ).

The Code is as follows:


Var ready = (function (){
Var isReady = false,
Funs = [];
Function handle (e ){
If (isReady ){
Return;
}
If (e. type = 'readystatechang' & (document. readyState! = 'Interactive '& document. readyState! = 'Complete ')){
Return;
}
For (var I = 0; I <funs. length; I ++ ){
Funs [I]. call (document );
}
IsReady = true;
Funs = null;
}
If (document. addEventListener ){
Document. addEventListener ('domainloaded', handle, false );
Document. addEventListener ('readystatechang', handle, false );
Document. addEventListener ('load', handle, false );
}
Else if (document. attachEvent ){
Document. attachEvent ('onreadystatechang', handle );
Document. attachEvent ('onload', handle );
}
Return function ready (callback ){
If (isReady ){
Callback. call (document );
}
Else {
Funs. push (callback );
}
};
}());


PS:
The code of this function is referred to in the authoritative guide. The only difference is that a judgment document. readyState is added! = 'Interactive'

The Code is as follows:


If (e. type = 'readystatechang' & (document. readyState! = 'Interactive '& document. readyState! = 'Complete ')){
Return;
}


The order of interaction and completion status in each browser cannot be consistent. It depends on the content of the browser and page and adds this judgment document. readyState! = 'Interactive,
No matter which stage appears first, the code can be executed earlier.
Ii. Loading css and js as needed
According to the jQuery source code, a type function is written to return the parameter type.

The Code is as follows:


/**
*
* Determine the parameter type
* CreateTime: 2013/9/18
*
*/
Function type (obj ){
Var classTypes, objectTypes;
If (obj = null ){
Return String (obj );
}
ClassTypes = {};
ObjectTypes = ('boolean Number String Function Array Date RegExp Object error'). split ('');
For (var I = 0, len = objectTypes. length; I <len; I ++ ){
ClassTypes ['[object' + objectTypes [I] +'] = objectTypes [I]. toLowerCase ();
}
If (typeof obj = 'object' | typeof obj = 'function '){
Var key = Object. prototype. toString. call (obj );
Return classTypes [key];
}
Return typeof obj;
}


The Code is as follows:


// Load css as needed
Function loadCss (cssUrl, callback ){
Var elem, bl,
IsExecuted = false; // prevent two callback executions in ie9
If (cssUrl = null ){
Return String (cssUrl );
}
Elem = document. createElement ('link '),
Elem. rel = 'stylesheet ';
If (type (callback) === 'function '){
Bl = true;
}
// For ie
Function handle (){
If (elem. readyState === 'loaded' | elem. readyState === 'complete '){
If (bl &&! IsExecuted ){
Callback ();
IsExecuted = true;
}
Elem. onreadystatechange = null;
}
}
Elem. onreadystatechange = handle;
// For non-ie
If (bl &&! IsExecuted ){
Elem. onload = callback;
IsExecuted = true;
}
Elem. href = cssUrl;
Document. getElementsByTagName ('head') [0]. appendChild (elem );
}
// Js load as needed
Function loadScript (scriptUrl, callback ){
Var elem, bl,
IsExecuted = false; // prevent two callback executions in ie9
If (scriptUrl = null ){
Return String (fn );
}
Elem = document. createElement ('script ');
If (type (callback) === 'function '){
Bl = true;
}
// For ie
Function handle (){
Var status = elem. readyState;
If (status = 'loaded' | status = 'complete '){
If (bl &&! IsExecuted ){
Callback ();
IsExecuted = true;
}
Elem. onreadystatechange = null;
}
}
Elem. onreadystatechange = handle;
// For non-ie
If (bl &&! IsExecuted ){
Elem. onload = callback;
IsExecuted = true;
}
Elem. src = scriptUrl;
Document. getElementsByTagName ('head') [0]. appendChild (elem );
}


PS: when judging whether the link and script elements are loaded, the load event is mainly used. In browsers earlier than ie9, there is no load event, and ie adds a readystatechange event for them, through judgment
The readyState status of the element determines whether the element has been loaded. The strange thing is that in ie9 (Other browser versions may also exist), the element has both a load event and a readystatechange event, therefore, an isExecuted variable is added to the Code. If a callback is executed, it will not be executed any more, avoiding two callbacks.
Iii. Call Method

The Code is as follows:


LoadCss ('HTTP: // www.jb51.net/#/tbtx/miiee/css/base.css', function (){
Console. log ('css loaded completion ');
});
LoadScript ('HTTP: // www.jb51.net/#/tbtx/miiee/js/jquery.js', function (){
Console. log ('js Load completed ');
});
Ready (function (){
Console. log ('dom is ready! ');
});

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.