The default js is loaded synchronously. The "loading" here can be understood as parsing and execution, rather than "downloading". In the latest version of the browser, the browser uses a waterfall style for the resources requested by the code. Loading is not blocking, but the execution of js is always blocking. What problems does this cause? If my index page needs to load some js, but one of the requests does not get a response for a long time, it blocks the execution of the subsequent js code (synchronous loading), and the page rendering cannot continue (if the js introduction is in the head after the label).
<script type="text/javascript" src='http://china-addthis.googlecode.com/svn/trunk/addthis.js'></script>
<script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'></script>
this is a test
Copy after login
For example, the above code is saved as an index.html file. The main body of the page is a simple string, but after the code is executed, the page remains blank. , why? Because the requested js cannot be loaded for a long time (possibly due to Google being blocked, etc.), the execution of the subsequent code is blocked and the page cannot be rendered. Maybe you will suggest that if you put the js code before
, the page will be rendered first! Good method, we try to put js behind:
this is a test
<script type="text/javascript" src='http://china-addthis.googlecode.com/svn/trunk/addthis.js'></script>
<script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'></script>
Copy after login
The page is rendered instantly, "this is a test" also quickly appears in the foreground, and the world seems to be calm, However:
this is a test
<script type="text/javascript" src='http://china-addthis.googlecode.com/svn/trunk/addthis.js'></script>
<script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'></script>
Copy after login
I simply added a piece of code based on the previous code, but "hello world" cannot be output on the console. Obviously, the previous js request is blocked. When loading the code behind, we suddenly realized that changing the loading position of js can only change the rendering of the page. However, it is of no use to the loading of js, and js will still block.
Implementing js asynchronous loading
Our requirement seems to be very simple. It can output a string in the console while the page is loading. To put it more simply, it is to request the first While segmenting the js provided by Google, continue to execute the following js, which is to implement asynchronous loading of js.
The most common approach is to dynamically generate script tags:
<body>
this is a test
<script type="text/javascript">
~function() {
var s = document.createElement('script');
s.src = 'http://china-addthis.googlecode.com/svn/trunk/addthis.js';
document.body.appendChild(s);
}();
</script>
<script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'></script>
<script type="text/javascript">
console.log('hello world');
</script>
</body>
Copy after login
But there is still a problem. This loading method will prevent the onload event before the loading is completed. Triggered, and now the code of many pages has to perform additional rendering work when onloading, so it will still block the initialization processing of some pages:
<body>
this is a test
<script type="text/javascript">
~function() {
// function async_load() {
var s = document.createElement('script');
s.src = 'http://china-addthis.googlecode.com/svn/trunk/addthis.js';
document.body.appendChild(s);
// }
// window.addEventListener('load', async_load, false);
}();
window.onload = function() {
var txt = document.createTextNode(' hello world');
document.body.appendChild(txt);
};
</script>
<script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'></script>
</body>
Copy after login
For example, the above The code cannot render "hello world" well. We only need to remove the comments and let the js provided by Google start loading asynchronously on onload. This solves the problem of blocking the onload event from being triggered.
Added DOMContentLoaded and OnLoad events DOMContentLoaded: The page (document) has been parsed and the dom elements in the page are available. However, the images and subframes referenced in the page may not have been loaded yet. OnLoad: All resources of the page are loaded (including images). The browser's loading progress stops at this point. These two time points divide the page loading timeline into three stages.
The above seems to be a better solution to this problem, but html5 provides a simpler method, the async attribute!
this is a test
<script type="text/javascript" src='http://china-addthis.googlecode.com/svn/trunk/addthis.js' async='async'></script>
<script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'></script>
<script type="text/javascript">
console.log('hello world');
</script>
Copy after login
async is a new attribute of html5. The async attribute specifies that once the script is available, it will be executed asynchronously (it will be executed immediately once downloaded).
It should be noted that the async attribute only applies to external scripts (only when using the src attribute)
The defer attribute is often mentioned together with async:
this is a test
<script type="text/javascript" src='http://china-addthis.googlecode.com/svn/trunk/addthis.js' defer='defer'></script>
<script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js'></script>
<script type="text/javascript">
console.log('hello world');
</script>
Copy after login
It seems that the implementation effect is similar, but is it really the same? Let's take a look at the definition of the defer attribute.
In the past, defer only supported IE hacks, but now the emergence of HTML5 has begun to fully support defer. The defer attribute specifies that the script will not be executed until the page has finished loading. The defer attribute only applies to external scripts (only when using the src attribute). ps: The defer supported by IE does not seem to be the case, because I have no interest in IE and will not delve into it. If you are interested, you can check the relevant information.
Since async and defer often appear together, let’s analyze them!
If there are no async and defer attributes (assigned to true, the same below), the browser will immediately execute the current js script and block subsequent scripts; if there is an async attribute, the process of loading and rendering subsequent document elements It will be done in parallel with the loading and execution of the current js (asynchronously); if there is a defer attribute, then the process of loading subsequent document elements will be done in parallel with the loading of script.js (asynchronously), but the execution of script.js will be done in all elements ( DOM) parsing is completed, but before the DOMContentLoaded event is fired.
Let’s take a look at a picture stolen from the Internet:
The blue line represents network reading, and the red line represents execution time, both of which are for scripts ; the green line represents HTML parsing.
This picture tells us the following key points (excerpted from the difference between defer and async):
defer and async are the same in terms of network reading (downloading) , both are asynchronous (compared to HTML parsing)
The difference between them lies in when the script is executed after it is downloaded. Obviously defer is the closest to our application script loading and execution Requirements
this is a test
<script type="text/javascript" src='http://china-addthis.googlecode.com/svn/trunk/addthis.js' defer='defer'></script>
<script type="text/javascript" src='http://libs.baidu.com/jquery/2.0.0/jquery.min.js' defer='defer'></script>
<script type="text/javascript" src='index.js' defer='defer'></script>
console.log('hello world');
The above is the detailed content of Several JavaScript asynchronous loading related issues. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.
Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side
WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology
Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price
Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order
How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.
JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We
With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese