This is the 18th day of my participation in the August More Text Challenge.

JS lazy loading, that is, loading JavaScript files after the page has finished loading, helps speed up page loading

Generally, there are the following ways:

  • The defer attribute
  • Async attributes
  • Use jQuery’s getScript method
  • Use the setTimeout delay method
  • Let JS load last

1. The defer attribute

HTML 4.01 defines an attribute called defer for the

Such as:

<! DOCTYPE html><html>
    <head>
        <title>Defer attribute tests</title>
        <script defer="defer" src="cs1.js"></script>
        <script defer="defer" src="cs2.js"></script>
    </head>
    <body>
        <! -- Page content --! > </body> </html>
Copy the code

Although

2. The async attributes

HTML5 defines async properties for

Purpose: To prevent pages from waiting for scripts to download and execute, thus asynchronously loading the rest of the page. The asynchronous script must be executed before the page load event. There is no guarantee that the scripts will be executed in order

Such as:

<! DOCTYPE html><html>
    <head>
        <title>Defer attribute tests</title>
        <script async src="cs1.js"></script>
        <script async" src="cs2.js"></script>
    </head>
    <body>
        <! -- Page content --! > </body> </html>
Copy the code

Async, like defer, does not block other resource downloads, so it does not affect page loading.

Disadvantages: can’t control the loading order

3. Use jQuery’s getScript() method

    $.getScript("cscs.js".function(){ // The callback function is executed after the file is successfully retrieved
        console.log("Js finished loading")});Copy the code

4. Use setTimeout to delay the loading time

Lazy loading of JS code to allow more time for web pages to load

<script type="text/javascript">
    function add(){
        return 1+2:} $(function(){
        setTimeout('add()'.1000); // Delay 1 second
    })
</script>
Copy the code

5. Let JS load last

Files imported from outside of js are placed at the bottom of the page to allow JS to be imported last, thus speeding up page loading

For example, when an external JS script file is introduced, if it is put into the HEAD of HTML, the JS script will be loaded into the page before the page is loaded, and it will be put into the body. The JavaScript code will run in the order that the page is loaded down from the top, so we can put the files imported from outside js at the bottom of the page, so that JS is imported last, which speeds up the page loading