SoFunction
Updated on 2025-03-01

Specific use of lazy loading and preloading in js

Lazy loading (lazy loading) and preloading are commonly used methods of web optimization. .

1. Lazy loading (lazy loading)

Principle: When data is really needed, the data loading operation is actually performed.
Purpose: The delay loading mechanism is proposed to avoid some unnecessary performance overhead

Several ways to implement lazy loading

1. Let js finally load

How to use: Put the file imported from js at the bottom of the page
Purpose: Let js be introduced last, thereby speeding up page loading
illustrate:
The reason why the browser adopts synchronization mode is that the js file is usually loaded or the <script> tag is placed at the end of the structure, and it will prevent the browser from subsequent operations. Therefore, it is placed at the back. When the page structure and style are rendered, then js will be executed to improve the user experience.

2. defer attribute

How to use: Defer attribute is defined for the <script> tag.
Purpose: Let the script 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.

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;script src="" defer="defer"&gt;&lt;/script&gt;
  &lt;script src="" defer="defer"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;!-- Contents are placed here --&gt;
&lt;/body&gt;
&lt;/html&gt;

illustrate:

  • Although the <script> element is placed in the <head> element, the included script will delay the browser's </html> tag before executing it.
  • When the browser parses a script to a script and there is a defer, the browser will download scripts with the defer attribute in parallel without blocking the subsequent processing of the page.
  • All defer scripts are guaranteed to be executed in sequence. (But in fact, delay scripts do not necessarily execute in order, so it is better to include only one delay script)
  • The defer property only applies to external script files.

3. async attribute

How to use: The async attribute is defined for the <script> tag.
Purpose: The page does not wait for the script to be downloaded and executed, thereby loading other contents of the page asynchronously.

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;script src="" async&gt;&lt;/script&gt;
  &lt;script src="" async&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;!-- Contents are placed here --&gt;
&lt;/body&gt;
&lt;/html&gt;

The browser will download the script immediately, but it will not hinder other operations in the page, such as downloading other resources or waiting for other scripts to be loaded. The process of loading and rendering subsequent document elements and the loading and execution of loading are carried out in parallel. This process is asynchronous. They will be completed before the onload event.

illustrate:

  • The browser will download the script immediately, but it will not hinder other operations in the page, the process of loading and rendering subsequent document elements, and the loading and execution of the script will be carried out in parallel.
  • This process is asynchronous and they will be completed before the onload event.
  • All defer scripts do not control the order of loading. .
  • The asyncr attribute is only applicable to external script files.

4. Dynamically create DOM method

//These codes should be placed in front of the </body> tag (close to the bottom of the HTML file)&lt;script type="text/javascript"&gt;
  function downloadJSAtOnload() {
    varelement = ("script");
     = "";
    (element);
  }
  if ()
   ("load",downloadJSAtOnload, false);
  else if ()
   ("onload",downloadJSAtOnload);
  else
    =downloadJSAtOnload;
&lt;/script&gt;

5. Use jquery's getScript method

How to use:

(url,success(response,status))
  • url (must write): the URL string to be requested
  • success(response,status) (optional): Specifies the callback function executed after the request is successful.

The parameters in it
response - contains result data from the request
status - contains the requested status ("success", "notmodified", "error", "timeout" or "parserererror")

Purpose: Load and execute JavaScript files via HTTP GET request.

//Load and execute:$.getScript("");
//Load and execute, and display information after success$.getScript("", function(){
 alert("Script loaded and executed.");
});

6. Use setTimeout to delay loading time

Purpose: Delay loading js code, leaving time for web page loading

&lt;script type="text/javascript"&gt;
 function A(){
  $.post("/lord/login",{name:username,pwd:password},function(){
   alert("Hello World!");
  })
 }
 $(function (){
  setTimeout("A()",1000); //Delay 1 second })
&lt;/script&gt;

Common examples - lazy image loading

Principle: An image is a <img> tag. Whether the browser initiates the request image is based on the src attribute of <img>. Therefore, the key to lazy loading is that when the image does not enter the visual area, do not assign a value to the <img>'s src first, so that the browser will not send a request, and wait until the image enters the visual area before assigning a value to src.

<img class="lazy" src="img/" lazy-src="img/" >
<img class="lazy" src="img/" lazy-src="img/" >
function lazyload(){
 var visible;
 $('img').each(function () {
 if( typeof($(this).attr("lazy-src"))!="undefined" ){ // Determine whether the image needs to be lazy to load  visible = $(this).offset().top - $(window).scrollTop(); //The distance from the top of the picture  if ((visible &gt; 0) &amp;&amp; (visible &lt; $(window).height())) {// Determine whether the picture is in the visible area    visible = true;// The picture is in the visible area  } else {
    visible = false;// The picture is not in the visible area  }
  if (visible) {
    $(this).attr('src', $(this).attr('lazy-src'));
  }
 }
 });
}
 // Open the page to trigger the function lazyload();
 // Trigger function when scrolling  =function(){
 lazyload(imgs);
 }

2. Preload

Principle: Load the image in advance, and render it directly from the local cache when the user needs to view it.
Purpose: Sacrifice front-end performance in exchange for user experience, so that users' operations can be reflected as quickly as possible.

Several ways to implement preloading

1. css implementation

Principle: The image can be preloaded on the off-screen background through the background property of CSS. As long as the paths of these images remain unchanged, the browser uses preloaded (cache) images during rendering when they are called elsewhere on the web page. Simple, efficient, and does not require any JavaScript.

#preload-01 { background: url(/) no-repeat -9999px -9999px; }

#preload-02 { background: url(/) no-repeat -9999px -9999px; }

#preload-03 { background: url(/) no-repeat -9999px -9999px; }

2. js preloaded pictures

Principle: Preload by writing functions. Encapsulate the script into a function and use addLoadEvent() to delay the preload time until the page is loaded.

function preloader() {
  if () {
    var img1 = new Image();
    var img2 = new Image();
    var img3 = new Image();
     = "/path/to/";
     = "/path/to/";
     = "/path/to/";
  }
}
function addLoadEvent(func) {
  var oldonload = ;
  if (typeof  != 'function') {
     = func;
  } else {
     = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(preloader);

3. Use ajax to implement preloading

Principle: Use Ajax to implement image preloading method. Using DOM, not only preload images, but also preload CSS, JavaScript and other related things.

 = function() {
  setTimeout(function() {
    // XHR to request a JS and a CSS
    var xhr = new XMLHttpRequest();
    ('GET', '/');
    ('');
    xhr = new XMLHttpRequest();
    ('GET', '/');
    ('');
    // preload image
    new Image().src = "/";
  }, 1000);
};

The above code is preloaded with "", "", and "". The 1000 millisecond timeout is to prevent the script from hanging, which causes functional problems on the normal page.

3. Comparison between lazy loading and preloading

1. Concept

Lazy loading is also called lazy loading: the data loading operation is actually performed when data is really needed.
Preload: Load in advance, and can be rendered directly from the local cache when the user needs to view it.

2. Difference

  • The nature of two technologies: the opposite behavior of the two is to load in advance, and the other is to be slow or even not loaded.
  • Lazy loading will have a certain pressure relief effect on the front end, while preloading will increase the pressure on the front end.

3. Meaning

The main purpose of lazy loading is to optimize front-end performance and reduce the number of requests or delayed requests.
Preloading is to sacrifice front-end performance in exchange for user experience and enable the user's operations to be reflected as quickly as possible.

4. Reference materials

【1】https:///article/
【2】https:///article/

This is the introduction to this article about the specific use of lazy loading and preloading in js. For more related lazy loading and preloading content in js, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!