I. A brief introduction to LABJS
Kyle Simpson
Role: Dynamically loading script files in parallel and managing the execution order of the Load script files
Official website: http://www.labjs.com/
Second, about the use of LABJS
The following example source link: http://www.au92.com/archives/labjs.html
A more complete and detailed description: http://labjs.com/documentation.php
Example 1:
$LAB. Script ("Script1.js"). Script (" script2.js"). script ("Script3.js") . Wait (function () {// Wait for all script to load and then execute this code block script1func (); Script2func (); Script3func (); });
Example 2:
$LAB. Script ({src: "script1.js", type: "Text/javascript"}). script ("Script2.js") . Script ("Script3.js") . Wait (function () {//wait for all script to finish loading and then execute this block of code Script1func (); Script2func (); Script3func ();} );
Example 3:
$LAB. Script ("Script1.js", "Script2.js", "Script3.js") . Wait (function () {//wait for all script to load and then execute this block of code Script1func (); Script2func (); Script3func (); });
Example 4:
$LAB. Script (["Script1.js", "Script2.js"], "script3.js") . Wait (function () {//wait for all script to load and then execute this block of code Script1func (); Script2func (); Script3func (); });
Example 5:
$LAB. Script ("Script1.js") . Wait () //Empty wait () just make sure that SCRIPT1 is executed before other code . Script ("Script2.js") // Script2 and SCRIPT3 depend on script1 . Script ("Script3.js") . Wait () //But Script2 and SCRIPT3 do not depend on each other and can be downloaded in parallel . Script ("Script4.js") //script4 relies on script1, Script2, and SCRIPT3. Wait (function () {Script4func ();});
Example 6:
$LAB. Script ("Script1.js") //SCRIPT1, SCRIPT2, and SCRIPT3 have no dependencies, . Script ("Script2.js") // Therefore, you can execute the. Script in any order ("Script3.js") . Wait (function () { ///if required, this can of course execute the JavaScript function alert (" Scripts 1-3 is loaded! "); }) . Script ("Script4.js") //dependent on SCRIPT1, Script2 and Script3 . Wait (function () {Script4func ();});
Example 7:
$LAB. SetOptions ({alwayspreserveorder:true})//Set wait between each script . Script ("Script1.js")//Script1, SCRIPT2, SCRIPT3, SCRIPT4 depend on each other . Script ("Script2.js")//and sequentially execute after downloading in parallel. Script (" script3.js"). script ("Script4.js") . Wait (function () { script4func (); });
Example 8:
$LAB. Script (function () { //' _is_ie ' value IE is true, non ie is false if (_is_ie) { return "ie.js"; If it is IE then this JS will be loaded }else{ return null; If it is not IE this code will be skipped } }) . Script ("Script1.js")
. Wait ();
Three, the LABJS mainly uses the loading way
LABJS dynamic load script file, refers to the page of the JS script execution, through a variety of methods to load external JS (mainly different from the HTML page, through the <script> tag statically loaded script)
There are many ways to load scripts dynamically, and the pros and cons are not mentioned here, and interested children's shoes can be found in the reference link at the end of this article:).
There are three techniques used in LABJS, namely Script Element,XHR injection , and Cache Trick
First of these three kinds of loading methods for a brief introduction, the fourth part of the re-analysis of the LABJS source code implementation in the face of three different ways to use the scene
Script Element(labjs default to load mode)
The most common script dynamic loading method, the advantages are many, including: 1, the implementation of simple 2, can cross the domain 3, does not block the loading of other resources, etc.
Opera/firefox (old version): The order in which the scripts are executed is consistent with the order in which the nodes are inserted into the page
Ie/safari/chrome: Execution order cannot be guaranteed
Attention:
- In the new version of Firefox, the order of script execution does not necessarily coincide with the order in which the pages are inserted, but can be guaranteed sequentially by setting the Async property of the script tag to False
- Older versions of Chrome do not necessarily coincide with the order in which the scripts are inserted, but can be guaranteed sequentially by setting the Async property of the script tag to False
XHR Injection
The script file is loaded through an AJAX request and then executed in the following way:
- Eval: Common Ways
- XHR injection: Create a SCRIPT element and inject the contents of the loaded script file
Primary limitation: cannot cross domain
Cache Trick(strongly dependent on browser-based feature implementations, not recommended)
When you set the Type property of the script element to a value that the browser does not recognize, such as "Text/cache", "Text/casper", "Text/hellworld", and so on, the behavior of different browsers is as follows:
Ie/safari/chrome (old version): The script will load as usual, but will not execute, assuming the browser does not disable the cache, the loaded script is cached by the browser, when needed, only need to re-create a script tag, the type is set to the correct value, SRC points to the previously requested file URL (equivalent to reading the file from the cache)
Opera/firefox: Do not load
Note:
- Strong reliance on browser-based feature implementations, which may be invalidated by changes in browser features, are not recommended for use
- A new version of Chrome that sets the type of the script element to not "text/javascript" and no longer loads the script file
Iv. LABJS about Script load adoption scheme judgment
Ignoring technical details, a pseudo-code to describe the implementation of the LABJS, roughly:
First, determine whether the requested script is pre-loaded (whether to pre-load the judging condition to see the pseudo-code comment);
such as pre-loading, and then determine whether the browser supports true preload, such as support for the actual preload, then preload it, if not, to determine whether the requested script is the same domain as the current page, truthfully, using XHR injection, if no, using the cache Trick;
If you do not preload, determine that the browser branch does not support the async attribute of the script element (see pseudo-code comment), if so, set the Async property, and request a script file;
if (ifpreloadscript) {//If the requested script file is pre-loaded: 1, requires preload 2, browser supports preloaded if (supportrealpreloading) {//If true preload if (Suppo rtpreloadpropnatively) {//supports pre-loading of script and separation of loading and execution by setting the Preload property of the script tag://nich Olas C. Zakas Great God's wish, there is no browser support: http://www.nczonline.net/blog/2011/02/14/ Separating-javascript-download-and-execution/script.onpreload = callback; Script.newpreload = true; SCRIPT.SRC = TargetUrl; }else{Script.onreadystatechange = callback; In fact, IE browser, assuming that the specified script element of the SRC attribute, ie browser will immediately load script.src = TargetUrl; Even if the script element is not inserted into the page, callback is the pre-loaded callback}} else if (Insamedomain) {//Non-cross-domain, with XHR injection: The requested script is in the same domain as the current page XHR = new XMLHttpRequest (); Since the last judgment has been ruthlessly abandoned in this conditional branch, so boldly with the new XMLHttpRequest () bar Xhr.onreadystatechange = callback; Xhr.open ("GET", TargetUrl); Xhr.send (); } else{//The most helpless after strokes, the Cache Trick, the new Chromei has not been supported Script.onLoad = callback; Script.type = ' Text/cache '; SCRIPT.SRC = TargetUrl; }}else{if (cancontrlexecutionorderbyasync) {//If the script element's Async property is able to force parallel-loaded scripts to execute The proposal that Kyle's great God has pushed forward has been accepted and put into the draft by the HTML5 group: Http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order#My_Solution SCR Ipt.onload = callback; Script.async = false; Setting the async of the script element to false ensures that the execution order of the script is consistent with the order of the request SCRIPT.SRC = TargetUrl; } else{script.onload = callback; SCRIPT.SRC = TargetUrl; }}
In fact, when you create an IMG node on the page and point its src to a script file, in some browsers can also play the role of the file preload, then labjs the author did not think of this point?
Many of Labjs's users have asked Kyle about the problem, and key says: "If the existing load strategy is already able to meet the requirements, don't want to make the LABJS design more complicated (not the exact words)
Write it in the back.
Here is simply a brief introduction to the role, usage, and internal implementation of the LABJS, and an analysis of the implementation of the internal specific source code to the next article
If there are errors, please indicate, if there is a problem, welcome to reply and email further exchange:)
Resources:
OLDJ: "Labjs analysis"
Steve Souders: "Loading Scripts without Blocking"
Franky: Also said dynamic load script. ReadyState State of the script Element under IE
Troll i ' m png: "JS parallel loading, sequential execution"
Follow-up reading recommendations:
Nicholas C. Zakas the idea of script loading: http://www.nczonline.net/blog/2011/02/14/separating-javascript-download-and-execution/
Kyle Simpson proposal for script loading: http://wiki.whatwg.org/wiki/Dynamic_Script_Execution_Order#My_Solution
Kely Simpson response to a version of Firefox that removes script execution order: http://blog.getify.com/ff4-script-loaders-and-order-preservation/
Analysis of LABJS Source code