Application of Delayed Loading and Preloading in js

  • 2021-10-24 18:43:58
  • OfStack

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

1. Delayed loading (lazy loading)

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

Several methods to realize delayed loading

1. Let js last load

How to use: Put the files imported from js at the bottom of the page
Purpose: Let js be introduced last, so as to speed up page loading
Description:
The reason why the viewer is in synchronous mode is that it usually loads js files or puts < script > The tags are all at the back of the structure, which is also because it will prevent the browser from following operations, so put them at the back, and then execute js when the page structure and style are all rendered to enhance the user experience

2. defer Properties

How to use: < script > The tag defines the defer attribute.
Purpose: Let the script not affect the construction of the page when it is executed. That is, the script will be delayed until the entire page has been parsed before execution


<!DOCTYPE html>
<html>
<head>
  <script src="test1.js" defer="defer"></script>
  <script src="test2.js" defer="defer"></script>
</head>
<body>
<!--  Put the content here  -->
</body>
</html>

Description:

Although < script > Elements are placed in the < head > Element, but the included script delays the browser's encounter < /html > Tag before executing. When the browser resolves to the script script and has an defer, the browser downloads the script 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, the delay script does not necessarily execute in order, so it is best to include only one delay script.) The defer property applies only to external script files.

3. async Properties

How to use: < script > The tag defines the async attribute.
Purpose: Load other contents of the page asynchronously without letting the page wait for the script to download and execute.


<!DOCTYPE html>
<html>
<head>
  <script src="test1.js" async></script>
  <script src="test2.js" async></script>
</head>
<body>
<!--  Put the content here  -->
</body>
</html>

The browser downloads the script immediately, but does not prevent other actions on the page, such as downloading other resources or waiting for other scripts to load. The loading and rendering of subsequent document elements is done in parallel with the loading and execution of main. js, which is asynchronous. They will be completed before the onload event.

Description:

The browser downloads the script immediately, without prejudice to other operations on the page, loading and rendering subsequent document elements and loading and execution of the script 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 applies only to external script files.

4. Dynamic creation of DOM mode


// These codes should be placed in the </body> Before label ( Approach HTML Bottom of file )
<script type="text/javascript">
  function downloadJSAtOnload() {
    varelement = document.createElement("script");
    element.src = "defer.js";
    document.body.appendChild(element);
  }
  if (window.addEventListener)
   window.addEventListener("load",downloadJSAtOnload, false);
  else if (window.attachEvent)
   window.attachEvent("onload",downloadJSAtOnload);
  else
   window.onload =downloadJSAtOnload;
</script>

5. getScript method using jquery

Usage:


Query.getScript(url,success(response,status))
url (required): The URL string to be requested success (response, status) (optional): Specifies the callback function to be executed after a successful request.

Parameters in which
response-Contains the result data from the request
status-Contains the status of the request ("success", "notmodified", "error", "timeout", or "parsererror")

Purpose: Load and execute an JavaScript file via an HTTP GET request.


// Load and execute  test.js : 
$.getScript("test.js");
// Load and execute  test.js  Display information on success 
$.getScript("test.js", function(){
 alert("Script loaded and executed.");
});

6. Load time using setTimeout delay method

Purpose: Delay loading js code to allow time for web page loading


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

Common Example-Lazy Loading of Pictures

Principle: One picture is one < img > Tag, whether the browser initiates the request picture is based on < img > src attribute, so the key to lazy loading is that when the picture does not enter the visual area, it will not be given first < img > src, so that the browser will not send a request, wait until the picture is in the visual area before assigning src.


<img class="lazy" src="img/loading.gif" lazy-src="img/pic1.jpg" >
<img class="lazy" src="img/loading.gif" lazy-src="img/pic2.jpg" >

function lazyload(){
 var visible;
 $('img').each(function () {
 if( typeof($(this).attr("lazy-src"))!="undefined" ){ //  Determine whether the picture needs lazy loading 
  visible = $(this).offset().top - $(window).scrollTop(); // Distance from the top of the picture 
  if ((visible > 0) && (visible < $(window).height())) {//  Determining whether the picture is in the visible area 
    visible = true;//  Picture in the visual area 
  } else {
    visible = false;//  Picture is not in the visible area 
  }
  if (visible) {
    $(this).attr('src', $(this).attr('lazy-src'));
  }
 }
 });
}
 //  Open the page trigger function 
 lazyload();
 //  Trigger function when scrolling 
 window.onscroll =function(){
 lazyload(imgs);
 }

2. Preload

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

Several methods to realize preloading

1. css implementation

How it works: Pictures can be preloaded onto an off-screen background via the background property of CSS. As long as the path of these pictures remains the same, when they are called elsewhere on the Web page, the browser will use the preloaded (cached) pictures during rendering. Simple and efficient, without any JavaScript.


#preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }

#preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }

#preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }

2. js Preload Picture

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


function preloader() {
  if (document.images) {
    var img1 = new Image();
    var img2 = new Image();
    var img3 = new Image();
    img1.src = "http://domain.tld/path/to/image-001.gif";
    img2.src = "http://domain.tld/path/to/image-002.gif";
    img3.src = "http://domain.tld/path/to/image-003.gif";
  }
}
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
addLoadEvent(preloader);

3. Preload with ajax

Principle: Using Ajax to realize picture preloading method, using DOM, not only preloading pictures, but also preloading CSS, JavaScript and other related things


<!DOCTYPE html>
<html>
<head>
  <script src="test1.js" async></script>
  <script src="test2.js" async></script>
</head>
<body>
<!--  Put the content here  -->
</body>
</html>
0

The above code preloads "preload. js", "preload. css", and "preload. png". The 1000-millisecond timeout prevents scripts from hanging and causing functional problems on normal pages.

3. Comparison of lazy loading and preloading

1. Concepts

Delayed loading is also called lazy loading: data loading is performed when data is really needed.
Preload: Load ahead of time and render directly from the local cache when the user needs to view it

2. Differences

The essence of the two technologies: the behavior of the two is opposite, one is to load in advance, and the other is to load slowly or even not. Lazy loading will relieve the pressure of the front end, while preloading will increase the pressure of the front end.

3. Meaning

The main purpose of lazy loading is to optimize front-end performance and reduce the number of requests or delay the number of requests.
Preloading sacrifices front-end performance in exchange for user experience, so that the user's operation can be reflected as quickly as possible.

4. References

"1" https://www.ofstack.com/article/154930. htm
"2" https://www.ofstack.com/article/57579. htm


Related articles: