Details labjs dynamically load JS files on Demand _javascript tips

Source: Internet
Author: User
Tags deprecated file url script tag

Labjs is a small JavaScript tool used to load JavaScript files as needed, by using the tool to enhance the performance of the page, to avoid loading JavaScript files that are not needed, and to implement dynamic parallel loading of script files. and manage the execution order of the load script files.

Simple example

$LAB
. Script ("Script1.js", "Script2.js", "Script3.js")
. Block (function () {
  //wait for all to load, then do Something
  Script1func ();
  Script2func ();
  Script3func ();
});

Some examples of the following labjs are introduced:
Example 1:

$LAB. Script ("Script1.js"). Script ("Script2.js").
  Script (
  "Script3.js")
  . Wait (function () {// Wait for all script to load and 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 () {/) waits for all script to load and executes this block of code
    Script1func ();
    Script2func ();
    Script3func ();
  });

Example 3:

$LAB
  . Script ("Script1.js", "Script2.js", "Script3.js")
  . Wait (function () {//Waiting 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 () {//Waiting 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 relies on script1
  . Script ("Script3.js"). Wait ()//But Script2 and SCRIPT3 are not interdependent and can be downloaded in parallel
  . Script ("Script4.js")// SCRIPT4 relies on script1, Script2 and Script3
  . Wait (function () {Script4func ();});

Example 6:


  there is no dependency between $LAB. Script ("Script1.js")//SCRIPT1, Script2, and Script3,
  . Script ("Script2.js")//So can be executed in any order
  . Script ("Script3.js")
  . Wait (function () {//If necessary, you can certainly execute JavaScript function
    alert ("Scripts 1-3 are 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 sequential execution after parallel download. 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 not IE this code will be skipped
    }
  })
  . Script ("Script1.js")
  . Wait ();

LABJS Loading mode

LABJS Dynamic Loading 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 static loading of the script)

There are a lot of ways to load scripts dynamically, with different pros and cons, not to be discussed here, and interested children's shoes can see 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 all three kinds of loading methods are introduced briefly, the fourth part of the analysis of LABJS source code implementation in the face of three different ways to use the scene

Script Element (Labjs by default)

The most common script dynamic load way, has many advantages, including: 1, realize simple 2, can cross domain 3, will not block other resources loading, etc.

Opera/firefox (old version): Script execution is in the same order as the node is inserted into the page

Ie/safari/chrome: The order of execution cannot be guaranteed

Attention:

Under the new version of Firefox, the order of script execution is not necessarily the same as the order in which the page was inserted, but you can guarantee sequential execution by setting the script label's Async property to False

In older versions of Chrome, the order of script execution is not necessarily the same as the order in which the page was inserted, but you can guarantee sequential execution by setting the script label's Async property to False

XHR Injection
Load the script file through an AJAX request, and then execute it in the following ways:
Eval: Common Way
XHR injection: Create a SCRIPT element and inject the contents of the script file that you loaded into
Primary limit: Cannot cross domain
Cache Trick (Strong browser-dependent feature implementation, deprecated)
When you set the type attribute 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 loads as usual, but does not execute, assuming the browser does not disable caching, the loaded script is cached by the browser, and when needed, just recreate the script label and set the type to the correct value. SRC points to a previously requested file URL (equivalent to reading a file from the cache)
Opera/firefox: Do not load
Note:
Strong reliance on browser-specific feature implementations, which may be invalidated by changes in browser characteristics, deprecated
New version of the Chrome browser, the script element's type is set to not "Text/javascript", and no more loading of the scripts file.

LABJS on the scenario of script load adoption

Ignore the technical details, through a piece of pseudo code to describe the implementation of LABJS, roughly:
First of all, whether to preload the requested script (whether the pre-loading judgment conditions to see the pseudo code annotation);
such as preload, and then determine whether the browser support real preload, such as support for real preload, then preload; if not, judge whether the requested script is in the same domain as the current page, and use XHR injection, if not, using cache trick;
If you do not preload, judge that the browser support does not support the script element's async attribute (see pseudocode annotation), if so, set the Async property and request the script file;

if (ifpreloadscript) {//When the requested script file is preloaded: 1, requires preload 2, the browser supports preload if (supportrealpreloading) {//If support for true preload if (Supportprelo adpropnatively) {//Support to implement script preload by setting the script tag's preload property, and to detach load and execute//nicholas C. Zakas Great God's good wishes, not yet have browser branch
      Hold:/blog/2011/02/14/separating-javascript-download-and-execution/script.onpreload = callback;
      Script.newpreload = true;
    SCRIPT.SRC = TargetUrl;  }else{Script.onreadystatechange = callback;  Actually refers to IE browser, assuming that the script element of the SRC attribute, ie browser will immediately load script.src = TargetUrl; If the script element is not inserted into the page, callback is a 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 ie in this condition branch, so boldly with the new XMLHttpRequest () bar Xhr.onreadystatechange = callback;
    Xhr.open ("Get", targeturl);
  Xhr.send ();
    else{//Most helpless after the recruit, Cache trick, the new version Chromei has not supported script.onload = callback;  
    Script.type = ' Text/cache ';
  SCRIPT.SRC = TargetUrl; }}else{if (cancontrlexecutioNorderbyasync) {//If the script element's Async attribute can be enforced in parallel to load the//kyle of the great God's efforts to advance the proposal, which has now been accepted by the HTML5 panel and put into the draft:/DYNAMIC_SC
    Ript_execution_order#my_solution script.onload = callback;  Script.async = false;
  Set the script element's async to false to ensure that the script's execution order 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 a page and point its src to a script file that also works as a file preload in some browsers, does the LABJS author not think of it?

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.