What are the methods of lazy loading of JavaScript scripts? (notes)

original

Lazy loading means waiting for the page to load before loading the JavaScript file. js lazy loading helps to improve page loading speed.

Loading method:

1. Blocking loading

The usual default loading method, loading in front of the browser will prevent subsequent processing by the browser, for example, loading js will pause the rendering of the image. So it can be said that the js that needs to be loaded is placed at the end, so that the js is loaded last, and the page is displayed first.

2. Lazy loading

Lazy loading is where script execution is delayed until after the document has been fully parsed and displayed. Lazy loading of non-essential module code.

3. Asynchronous loading

Asynchronous loading is to download the js' script immediately without hindering other operations on the page.

 

Delay method:

  • defer attribute: Add defer attribute to the js script, this attribute will make the script loading and document parsing synchronously parsed, and then execute the script file after the document parsing is completed, so that the rendering of the page will not be blocked. Multiple scripts with the defer attribute set end up executing sequentially by specification, but this may not be the case in some browsers.

  • async attribute: Add async attribute to the js script. This attribute will load the script asynchronously and will not block the parsing process of the page. However, the js script will be executed immediately after the script is loaded. At this time, if the document is not parsed, it will also be blocked. The execution order of scripts with multiple async attributes is unpredictable, and generally will not be executed sequentially in the order of the code.

    tip: HTML 5 defines the async attribute for the <script> tag.

  • Dynamically create DOM method: The method of dynamically creating DOM tags can monitor the loading event of the document, and then dynamically create script tags to import js scripts after the document is loaded.

  • Use the setTimeout delay method: set a timer to delay loading js script files

  • Let JS load last: Put the js script at the bottom of the document to make the js script load and execute at the end as much as possible.

Guess you like

Origin blog.csdn.net/qq_42533666/article/details/129068532