Home Web Front-end JS Tutorial A brief analysis of JavaScript asynchronous loading_javascript skills

A brief analysis of JavaScript asynchronous loading_javascript skills

May 16, 2016 pm 04:24 PM
javascript Asynchronous loading

Foreword

I believe you have encountered many problems with JavaScript script loading. Mainly in a few points——

1> File loading, file dependency and execution order issues caused by synchronous scripts and asynchronous scripts
2> Performance optimization issues caused by synchronous scripts and asynchronous scripts


A thorough understanding of all aspects related to script loading will not only help solve practical problems, but also help grasp and implement performance optimization.

First look at any script tag code——


Copy code The code is as follows:



If placed above the , it will block all page rendering work, leaving the user in a "white screen of death" state until the script is loaded and executed. The script at the end of will only allow users to see a lifeless static page. The place where client-side rendering should be performed is scattered with ineffective controls and empty boxes. Get a test case -

Copy code The code is as follows:





Asynchronous loading script



I am the content




Among them, the content in test.js——


Copy code The code is as follows:

alert('I am the script code in the head. After executing the js here, the content rendering of the body will start!');


We will see that alert is a pause point, and at this time, the page is blank. But please note that the entire page has been loaded at this time. If the body contains tags with certain src attributes (such as the img tag above), the browser has already started loading related content. In short, please note that the working timing of the js engine and the rendering engine are mutually exclusive (some books call it the UI thread).

Therefore, we need - those scripts responsible for making the page look better and easier to use should be loaded immediately, while those scripts that can be loaded later should be loaded later.

1. Delayed execution of script

It is becoming more and more popular to place scripts at the end of the tag of the page. In this way, on the one hand, users can see the page faster, and on the other hand, scripts can directly operate on the loaded DOM elements. For most scripts, this "move" is a huge improvement. The page model is as follows——


Copy code The code is as follows:












This does speed up the rendering time of the page significantly, but be aware that this may give the user a chance to interact with the page before the bodyScript is loaded. The reason is that the browser cannot load these scripts until the entire document has been loaded, which can be a bottleneck for large documents sent over slow connections.

Ideally, the loading of the script should occur simultaneously with the loading of the document and not affect the rendering of the DOM. This way, you can run the script once the document is ready because the scripts have already been loaded in the order of the <script> tags. </p> <p></p> <p>We can use defer to fulfill this requirement, that is - </p> <p><br> </p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="92200" class="copybut" id="copybut92200" onclick="doCopy('code92200')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code92200"> <br> <script src="deferredScript.js"></script>


Adding the defer attribute is equivalent to telling the browser: Please start loading this script now, but please wait until the document is ready and all previous scripts with the defer attribute have finished running before running it.

In this way, placing the delay script in the head tag will bring all the benefits of placing the script in the body tag, and it will also greatly increase the loading speed of large documents. The page mode at this time is——


Copy code The code is as follows:












But not all browsers support defer (for some modern browsers, if defer is declared, their internal scripts will not perform document.write and DOM rendering operations. IE4 all supports the defer attribute). This means that if you want to ensure that your delayed script can run after the document is loaded, you must encapsulate all the delayed script code in a structure such as jQuery's $(document).ready. It's worth it because almost 97% of your visitors get the benefits of parallel loading, while the other 3% still have access to fully functional JavaScript.

2. Complete parallelization of scripts

Make the loading and execution of scripts one step faster. I don’t want to wait for defer scripts to run one after another (defer reminds us of an orderly queuing scenario of quietly waiting for the document to load), nor do I want to wait until the document is ready before running these Scripts, I want to load as quickly as possible and run these scripts as quickly as possible. The async attribute of HTML5 comes to mind here, but be aware that it is a chaotic anarchy.

For example, we load two completely unrelated third-party scripts, the page runs just fine without them, and we don’t care which one runs first and which one runs last. Therefore, using the async attribute on these third-party scripts is equivalent to improving their running speed without spending a penny.

The async attribute is new to HTML5. The function is similar to defer, which allows DOM rendering while downloading the script. However, it will be executed as soon as possible after downloading (that is, the JS engine will be executed as soon as it is idle), and there is no guarantee that the script will be executed in order. They will complete before the onload event.

Firefox 3.6, Opera 10.5, IE 9 and the latest Chrome and Safari all support the async attribute. You can use async and defer at the same time, so that all IE after IE 4 support asynchronous loading, but be aware that async will overwrite defer.

Then the page model at this time is as follows——

Copy code The code is as follows:














Pay attention to the order of execution here - each script file is loaded, then headScript.js is executed, and then defferedScript.js is loaded in the background while the DOM is rendering. Then at the end of DOM rendering, defferedScript.js and the two asynchronous scripts will be run. It should be noted that for browsers that support the async attribute, these two scripts will run out of order.

3. Programmable script loading

Although the functions of the above two script attributes are very attractive, they are not widely used due to compatibility issues. Therefore, we use scripts more often to load other scripts. For example, we only want to load a script to those users who meet certain conditions, which is often referred to as "lazy loading".

At the browser API level, there are two reasonable ways to grab and run server scripts -

1> Generate ajax request and use eval function to process the response

2> Insert

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1248
24
c# What is delegation and what problem does it solve? c# What is delegation and what problem does it solve? Apr 04, 2024 pm 12:42 PM

Delegation is a type-safe reference type used to pass method pointers between objects to solve asynchronous programming and event handling problems: Asynchronous programming: Delegation allows methods to be executed in different threads or processes, improving application responsiveness. Event handling: Delegates simplify event handling, allowing events such as clicks or mouse movements to be created and handled.

Effectively deal with situations where jQuery .val() doesn't work Effectively deal with situations where jQuery .val() doesn't work Feb 20, 2024 pm 09:36 PM

Title: Methods and code examples to solve the problem that jQuery.val() does not work. In front-end development, jQuery is often used to operate page elements. Among them, getting or setting the value of a form element is one of the common operations. Usually, we use jQuery's .val() method to operate on form element values. However, sometimes you encounter situations where jQuery.val() does not work, which may cause some problems. This article will introduce how to effectively deal with jQuery.val(

The key optimization mode to improve website speed, every front-end developer must master! The key optimization mode to improve website speed, every front-end developer must master! Feb 02, 2024 pm 05:36 PM

A must-have for front-end developers: master these optimization modes and make your website fly! With the rapid development of the Internet, websites have become one of the important channels for corporate promotion and communication. A well-performing, fast-loading website not only improves user experience, but also attracts more visitors. As a front-end developer, it is essential to master some optimization patterns. This article will introduce some commonly used front-end optimization techniques to help developers better optimize their websites. Compressed files In website development, commonly used file types include HTML, CSS and J

How to read html How to read html Apr 05, 2024 am 08:36 AM

Although HTML itself cannot read files, file reading can be achieved through the following methods: using JavaScript (XMLHttpRequest, fetch()); using server-side languages ​​(PHP, Node.js); using third-party libraries (jQuery.get() , axios, fs-extra).

How to optimize the performance of H5 page production How to optimize the performance of H5 page production Apr 06, 2025 am 06:24 AM

Through network requests, resource loading, JavaScript execution and rendering optimization, the performance of H5 pages can be improved and a smooth and efficient page can be created: resource optimization: compressed images (such as using tinypng), simplified code, and enabled browser caching. Network request optimization: merge files, use CDN, and load asynchronously. JavaScript optimization: reduce DOM operations, use requestAnimationFrame, and make good use of virtual DOM. Advanced skills: code segmentation, server-side rendering.

Sharing of PHP search function optimization tips Sharing of PHP search function optimization tips Mar 06, 2024 am 11:12 AM

PHP search function has always been a very important part of website development, because users often use the search box to find the information they need. However, many websites have problems such as low efficiency and inaccurate search results when implementing search functions. In order to help you optimize PHP search function, this article will share some tips and provide specific code examples. 1. Use full-text search engines. Traditional SQL databases are less efficient when processing large amounts of text content. Therefore, it is recommended to use full-text search engines, such as Elasticsearch, Solr, etc.

Demystifying Website Performance Optimization: Master these methods to make your website speed soar! Demystifying Website Performance Optimization: Master these methods to make your website speed soar! Feb 03, 2024 am 08:00 AM

Website performance optimization revealed: Master these methods to make your website fly! With the rapid development of the Internet, websites have become an important channel for corporate promotion, product display, and communication and interaction. However, when users visit the website, if the loading speed is too slow and the response time is too long, the user experience will be greatly reduced, and may even directly cause users to leave. Therefore, website performance optimization is becoming increasingly important. So, what is website performance optimization? Simply put, website performance optimization is to improve the loading speed of the website through a series of methods and technical means.

How to introduce external js into html How to introduce external js into html Apr 11, 2024 am 06:18 AM

To include an external JS file in HTML, use the <script> tag and specify the URL of the file to load. You can also specify type, defer, or async attributes to control how loading and execution occur. Typically, the <script> tag should be placed at the bottom of the <body> section to avoid blocking page rendering.

See all articles