JS lazy loading, that is, after the page is loaded, then loading the JavaScript file.
JS lazy loading helps improve page loading speed.
There are generally the following ways:
-
- defer attribute
- async attribute
- Dynamically create DOM
- GetScript method using jQuery
- Use setTimeout delay method
- Let JS load last
1. defer attribute
HTML 4.01 is<script>
Tags are defineddefer
property.
Purpose: Indicates that the script will not affect the construction of the page when it is executed. In other words, the script will be delayed until the entire page has been parsed before execution.
exist<script>
Set in the elementdefer
The attribute is equal to telling the browser to download immediately, butDelayed execution。
<!DOCTYPE html>
<html>
<head>
<script src="" defer="defer"></script>
<script src="" defer="defer"></script>
</head>
<body>
<!-- Put content here -->
</body>
</html>
Note: Although<script>
The elements are placed<head>
The script included in the element, but the included script will delay the browser encounter</html>
After tagging, execute.
HTML5
The specification requires scripts to be executed in the order in which they appear. In reality, delay scripts are not necessarily executed in sequence.
defer
propertyApplicable to external script files only. Implementations that support HTML5 ignore embedded script settingsdefer
property.
2. async attribute
HTML5 is<script>
Tags are definedasync
property. anddefer
The properties are similar, and are used to change the behavior of processing scripts. same,Applicable to external script files only。
Purpose: Do not allow the page to wait for the script to be downloaded and executed, thusAsynchronous loading of other contents on the page。
The asynchronous script will be executed before the page load event.
There is no guarantee that the scripts will be executed in order.
<!DOCTYPE html>
<html>
<head>
<script src="" async></script>
<script src="" async></script>
</head>
<body>
<!-- Put content here -->
</body>
</html>
Like defer, async will not block other resources from downloading, so it will not affect the loading of the page.
Disadvantages: Cannot control the order of loading
3. Dynamically create DOM method
//These codes should be placed in</body>Before the tag (close to the bottom of the HTML file)<script type="text/javascript">
function downloadJSAtOnload() {
varelement = ("script");
= "";
(element);
}
if ()
("load",downloadJSAtOnload, false);
else if ()
("onload",downloadJSAtOnload);
else
=downloadJSAtOnload;
</script>
4. Use jQuery's getScript() method
$.getScript("",function(){//Callback function, function executed after successfully obtaining the file
("Script loading complete")
});
5. UsesetTimeout
Delay method
6. Let JS load last
Put the files introduced outside js at the bottom of the page to allow js to be introduced last, thereby speeding up page loading