High-performance JavaScript: loading and execution

Source: Internet
Author: User

Before getting started, I will introduce you to a good book titled high performance.JavaScriptYou may wish to take a look. In this article, I will share some of my achievements in reading this book.

Blocking feature:
JSThere is a silent blocking feature, that is, whenBrowserWhen executing JavaScript code, you cannot do anything else at the same time, whether the code is embedded or external.

Script location:
When the browser encounters a <script> label that introduces an external JS file, it stops all work to download and parse and execute it. In this process, page rendering and user interaction are completely blocked, to avoid page loading pauses or even the appearance of blank pages, JS scripts should be placed at the bottom of the page as much as possible. This is very important:

 
 
  1. <Html>
  2. <Head>
  3. <Title> untitled document </title>
  4. <Link rel = "stylesheet" type = "text/css" href = "styles.css"/>
  5. </Head>
  6. <Body>
  7. <P> page content... </P>
  8. <! -- Recommended location, at the bottom of the page: -->
  9. <Script type = "text/javascript" src = "file1.js"> </script>
  10. <Script type = "text/javascript" src = "file2.js"> </script>
  11. <Script type = "text/javascript" src = "file3.js"> </script>
  12. </Body>
  13. </Html>

Organization script:
In order to improve the above blocking situation, we should minimize the number of <script> tags on the page, which also takes into account the additional performance overhead caused by HTTP requests, that is to say, the number of Chinese and foreign link scripts on the page should be reduced.

You can manually Merge multiple of your JS files, or use a file similar to Yahoo! Real-time online services such as combo handler are implemented. For example, the <script> label below actually loads three JS files:

 
 
  1. <Html>
  2. <Head>
  3. <Title> untitled document </title>
  4. <Link rel = "stylesheet" type = "text/css" href = "styles.css"/>
  5. </Head>
  6. <Body>
  7. <P> page content... </P>
  8. <! -- Recommended location, at the bottom of the page: -->
  9. <Script type = "text/javascript" src = "http://yui.yahooapis.com/combo? File1.js & file2.js & file3.js "> </script>
  10. </Body>
  11. </Html>

Non-blocking script:
For blocking, several methods are provided to download JS scripts in parallel.

1. Delayed scripts

HTML4 defines a defer attribute for the <script> label, which can delay the execution of this Code. However, this attribute is only supported by IE4 + and Firefox 3.5 +. The <script> with the defer attribute declared will be loaded in the DOM and parsed and executed before the window. onload event is triggered:

 
 
  1. <script type="text/javascript" src="file1.js" defer></script> 

2. Dynamic script elements
This is the most common solution. You can use the DOM to dynamically create the <script> element and insert it into the document. The file starts to be downloaded when the element is added to the page, in this way, the file download and execution process will not block other processes on the page at any time.

However, you must note that the Code loaded in this way will be executed immediately. This requires a clear understanding of the role of each file and a reasonable execution order, it is necessary to track and ensure that the script is downloaded and ready. A load event is triggered when the <script> element is received by a non-IE browser, in IE, A readystatechange event is triggered and determined by the readyState attribute. The following functions are compatible with dynamic loading of a JS script:

 
 
  1. function load_script(url, callback)   
  2. {      var script = document.createElement('script');        
  3.        script.type = 'text/javascript';  
  4.        if (script.readyState)   
  5.        {  //IE   
  6.          script.onreadystatechange = functio()
  7. {          
  8.  if (script.readyState == 'loaded' || script.readyState == 'complete') 
  9. {
  10.                 script.onreadystatechange = null;
  11.                 callback();
  12.              }
  13.            }
  14.       } 
  15. else
  16. { //others
  17.         script.onload = function(){ 
  18.              callback(); }
  19.       }
  20.       script.src = url;
  21.       document.getElementsByTagName('head')[0].appendChild(script);
  22.   } 

You can save this function to a load_script.js file, and then use this function to load other scripts. To ensure the correct loading order, when loading multiple scripts, you can concatenate the execution of load_script () and put it at the bottom of the page as mentioned above. This is a perfect solution.

 
 
  1. <Script type = "text/javascript" src = "load_script.js"> </script>
  2. <Script type = "text/javascript">
  3. Load_script ('file1. js', function ()
  4. {
  5. Load_script ('file2. js', function ()
  6. {
  7. Load_script ('file3. js', functio (){
  8. // All loaded operations...
  9. });
  10. });
  11. });
  12. </Script>

3. XMLHttpRequest Script Injection

That is, loading through AJAX. However, this method cannot implement cross-origin loading and is not applicable to large websites.

Recommended non-blocking mode
The above work has certainly been completed by the cool people, and some excellent JS class libraries have been written for our use. They can solve the blocking problem of JS scripts well, implements parallel downloads, such as YUI3, LazyLoad, and LABjs.
 

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.