High-performance site optimization-ensures that execution order is maintained when scripts are loaded asynchronously

Source: Internet
Author: User

For the asynchronous loading of JS or CSS, can not control its order, can not guarantee that the load is over, and then deal with their own business, which caused us a great deal of trouble. There are now three ways to guarantee the order of execution. I personally recommend a third method. Use JS's onload event.

If the script is loaded in the usual way, it will not only block the download of other content in the page, but also block the rendering of all elements behind the script. Asynchronous load scripts can avoid this blocking phenomenon, which increases the speed of page loading. But there is a price to pay for performance improvements. The asynchronous execution of the code may appear competitive. Simply put, the script inside the page needs an identifier if it is defined in an external file, and when an external file is loaded asynchronously, there is a high likelihood of an undefined identifier error if the external file and internal script execution order are not guaranteed.

When there is a code dependency between the asynchronous loaded external script and the inline script, the two scripts need to be consolidated by a method that guarantees the order of execution.

How to ensure execution order

When an external script loads normally, he blocks the execution of inline code without an undefined identifier error due to a competing state. There are several techniques that can help us ensure the order of execution.

    • Hard-coded callbacks (hardcoded Callback)
    • Window Onlad
    • Timers (timer)
    • degrading Script Tags
Method 1: Hard-coded callbacks (hardcoded Callback)

Let the external script invoke internal script functions to ensure that the code is executed in order. For example, link

Inline code function init () {  createmenu (' examples ');} var domscript = document.createelement (' script ');d omscript.src = "Menu-with-init.js";d ocument.getelementsbytagname ( ' head ') [0].appendchild (Domscript);//external file function CreateMenu (ID) {  [...]} Callback to the main pageinit ();

  

This technique is possible if the developer can control both the master page and the external script. But we often call third-party JavaScript, such as jquery, and we can't drop callbacks in the jquery file. And this approach is less flexible, and once you change the callback function, you need to modify the external script at the same time.

Method 2:window Onload

Triggers the execution of in-line code by listening to the OnLoad event of the Window. This allows the execution order to be guaranteed as long as the external script is downloaded before window.onload. Some asynchronous loading techniques ensure that the external footstep is loaded before the Window.onload trigger:

    • Script in Iframe keeps sequential execution in IE, Firefox, Safari, Chrome, and Opera

    • Script DOM keeps sequential execution in Firefox, Safari, and Chrome

By using one of these techniques, the parallel download can be implemented by window.onload triggering in-line script to ensure the execution sequence. Check our website demo. This example uses the script in Iframe method to load an external script that will block the OnLoad event in almost all browsers. The external script is embedded in the menu.php and then loaded with an IFRAME instead of loading the menu.js directly. Depending on the browser differences choose AddEventListener or attachevent than simple to use window.onload () better. More solutions for window.onload loading»

Window Onload's integration technique has two drawbacks: first, you must determine that the asynchronous script is loaded by blocking the Onload event. Second, it may cause deferred execution of code within the line. If the page has many other resources, such as slices, then after the execution of the external script loading, the code inside the window.onload must wait until the page is fully loaded before it can be executed. Typically inline scripting is best called immediately after an external script is downloaded and executed.

Method 3: Timers (timer)

Timer technology refers to the use of polling methods to ensure that in-line code execution, before the dependent external script has been loaded. "High-performance website Construction Advanced Optimization" in the book gives the demo can see link. Modify the in-line code to add a new function, Inittimer, to check for the existence of dependent namespaces and identifiers. If present, call the function that needs to be called, or, if it does not exist, call the Inittimer function again after the specified time period to check the namespace and identifier.

function Inittimer () {    if ("undefined" = = = typeof (Efws)) {        setTimeout (inittimer);    }    else {        init ();}    }

  

This technique has its drawbacks, too. If the event interval set in the SetTimeout method is too small, the cost of the page may be increased. Conversely, if the setting is too large, it can cause a delay between the completion of the external script loading and the execution of the in-line code. In the example above, if the external script fails to load, the script will never be able to detect the specified namespace, and the polling can go on indefinitely. The cost of maintenance is increased slightly, and the inline code is updated if the external file namespace and identifier are changed.

Method 4:script Onload

The previous integration techniques will increase the vulnerability, overhead, and delay of the page. The script onload method solves all of these problems by listening to the OnLoad event of the scripts. Link Given the differences between browsers, the OnLoad and onReadyStateChange event handlers for the script element are added. OnLoad works in other browsers and Opera is both valid.

var domscript=document.createelement ("script");D omscript.src= "Someting.js";D omscript.onloaddone=false;d Omscript.onload=function () {domscript.onloaddone=true;init ();} Domscript.onreadystatechange=function () {if ("loaded" = = = Domscript.readystate | | "complete" = = = Domscript.readystate) &&! Domscript.onloaddone) {domscript.onloaddone=true;init ();}}

  

Script Onload is the preferred choice for consolidating asynchronous loading of external and inline scripts . No external identifiers are referenced, so maintenance is simple. Inline scripts can be executed immediately after an external script is loaded. At the same time, event handling is simple.

High-performance site optimization-Ensure that the execution sequence is persisted when the script is loaded asynchronously

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.