Five ways to load JavaScript scripts

Source: Internet
Author: User
Tags jquery library

JavaScript files (hereinafter referred to as script files) need to be referenced by an HTML file to run in the browser. There are different ways to reference script files in an HTML file, and we need to focus on the specific implementations of these approaches and the performance issues that these approaches can bring.

When the browser encounters (inline) <script> tags, the current browser has no way of knowing whether JavaScript will modify the page content. Therefore, the browser stops processing the page, executes the JavaScript code, and then continues parsing and rendering the page. The same applies to the use of the SRC attribute in JavaScript (i.e., out-of-chain JavaScript), where the browser must first take the time to download the code from the outer chain file and parse and execute it. In this process, page rendering and user interaction are completely blocked.

In other words: whenever the browser resolves to the <script> tag (inline or outside), the browser will (one rib) first download, parse, and execute the JavaScript code in that tag, blocking the download and rendering of all subsequent page content.

Mode one: procedure of the formula

The most traditional way is to insert the <script> tag inside the head tag.

However, this conventional approach hides serious performance problems. Based on the above description of the <script> tag characteristics, we know that in this example, when the browser resolves to the <script> tag, the browser stops parsing the content, and the script file is first downloaded, and the code is executed, which means that Subsequent test.css style files and <body> tags cannot be loaded, and because the <body> tag cannot be loaded, the page will naturally not render. So before the JavaScript code is fully executed, the page is blank.

<script type="text/javaScript" src="example.js"></script>
Way two: the classical procedure

Since the <script> tag blocks the loading of subsequent content, wouldn't it be possible to avoid such a bad situation after placing the <script> tag on all the page contents? Place all <script> tags at the bottom of the <body> tab as much as possible to avoid the effects of downloading the rest of the page.

Script parallel downloads have been implemented on the Ie8+ browser, but in some browsers (even if the script file is placed at the bottom of the <body> tab), the script in the page is still loaded one after the other. So we need the next method, namely: Dynamic load script.

Mode three: Dynamic scripting

With the Document Object Model (DOM), we can create almost anywhere on a page.

<script type=‘text/javascript‘>    var script = document.createElement(‘script‘);    script.type = ‘text/javaScript‘;    script.src = ‘file1.js‘;    document.getElementsByTagName(‘head‘)[0].appendChild(script);</script>

The code above dynamically creates an <script> tag for the outer chain file1 and adds it to the

无论在何时启动下载,文件的下载和执行过程不会阻塞页面其他进程(包括脚本加载)。

However, this method is also flawed. Scripts loaded in this way are executed as soon as the download is complete, meaning that the sequence of operations between multiple scripts is not guaranteed (except for Firefox and Opera). When a script has a dependency on another script, the error is likely to occur. For example, writing a jquery code requires the introduction of the jquery library, but the jquery code file that you write is likely to be downloaded and executed immediately, and then the browser will error--' jquery undefined ', because the jquery library is not yet downloaded. The following improvements were made:

<script type=' Text/javascript '>     function loadscript(URL, callback) {        varScript = Document.createelement (' script '); Script.type ="Text/javascript";//IE and opera support onreadystatechange        //Safari, Chrome, opera support onload        if(script.readystate) {//ieScript.onreadystatechange = function() {                if(Script.readystate = ="Loaded"|| Script.readystate = ="Complete") {Script.onreadystatechange =NULL;                Callback ();        }            }; }Else{//Other browsersScript.onload = function() {Callback ();        };        } script.src = URL; document.getElementsByTagName (' head ')[0].appendchild (script); }</script>

ReadyState, which includes the following values:
0: "Uninitialized" – Original state
1: "Loading" – Loading
2: "Loaded" – Loading complete
3: "Interactive" – not done yet
4: "Complete" – Script execution completed
  
Why do I write ":", because in Xhr, the readystate of the request is in the form of a number, that is, the left part of the ":", and when the node is loaded, the readystate is in the form of a string, that is, ":" To the right of the section.
Why to say this, of course, is for IE this fellow. Other browsers will issue the OnLoad event when the script is loaded, so there is no problem, but IE does not know what the onload is, so it is a unique faction.

How do you tell if the script is loaded? The general practice is to judge Script.readystate,ie is a pervert, even this value is not fixed, so need to do:

Script.readystate = = = ' Loaded ' | | Script.readystate = = = ' complete '

About the load judgment here, I refer to the design of several frameworks, in addition to requirejs more than a sentence event.type = = = ' Load ', mostly with the above paragraph, so I also use this sentence, die everyone together die.

One of the improvements in the code above is the addition of a callback function that is called after the corresponding script file has been loaded. This allows for sequential loading, as follows (assuming File2 relies on file1,file1 and file3 to be independent of each other):

loadScript(‘file1.js’,function(){ loadScript(‘file2.js’,function(){}); }); loadScript(‘file3.js’,function(){

File2 will start loading after the file1 is loaded, ensuring file1 is ready before file2 execution. File1 and File3 are downloaded in parallel, and do not affect each other. Although the Loadscript function is good enough, it is still a bit unsatisfactory--by analyzing the code, we know that the sequential loading in the Loadscript function is implemented as a blocking load of the script (as indicated in the Scarlet Letter section above). What we really want to do is--the scripts are downloaded synchronously and executed in the order they were loaded in parallel and executed sequentially.

Mode four: Labjs

The LABJS library can help us really achieve "parallel loading and sequential execution", the recommended wording is as follows:

<script src="Lab.js"></script><script type="Text/javascript">$LAB. Script ("Script1.js"). Wait (). Script ("Script2-a.js"). Script ("script2-b.js       "). Wait (function(){ initScript1 ();     InitScript2 ();     }). Script ("Script3.js"). Wait (function(){ initScript3 (); });</script>
Way Five: Requirejs
<script src="Require.js"></script><script type="Text/javascript"> require([ "Script1.js", "Script2-a.js", " script2-b.js", "s      Cript3.js " ],  function(){ initScript1 ();      InitScript2 ();     INITSCRIPT3 (); });    </script>

Five ways to load JavaScript scripts

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.