Delayed loading (lazy loading) and preloading are commonly used means of web optimization. . 1. Delayed loading (lazy loading) Principle: Data loading is performed only when data is really needed. Several ways to implement lazy loading 1. Let js load last Usage: Put the external js files at the bottom of the page Purpose: Let js be introduced last to speed up page loading Description: 2. The defer attribute How to use: Define the defer attribute for the <script> tag. <!DOCTYPE html> <html> <head> <script src="test1.js" defer="defer"></script> <script src="test2.js" defer="defer"></script> </head> <body> <!-- Put your content here --> </body> </html> illustrate:
3. async attribute Usage: Define the async attribute for the <script> tag. <!DOCTYPE html> <html> <head> <script src="test1.js" async></script> <script src="test2.js" async></script> </head> <body> <!-- Put your content here --> </body> </html> The browser will download the script immediately, but will not prevent other operations on the page, such as downloading other resources or waiting for other scripts to load. The process of loading and rendering subsequent document elements is done in parallel with the loading and execution of main.js, which is an asynchronous process. They will complete before the onload event. illustrate:
4. Dynamically create DOM//These codes should be placed before the </body> tag (near the bottom of the HTML 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. Use jQuery's getScript method Directions: Query.getScript(url,success(response,status))
The parameters Purpose: Load and execute JavaScript files via HTTP GET request. //Load and execute test.js: $.getScript("test.js"); // Load and execute test.js, and display information after success $.getScript("test.js", function(){ alert("Script loaded and executed."); }); 6. Use setTimeout to delay the loading time of the method Purpose: Delay loading of 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 second}) </script> Common Examples - Image Lazy Loading Principle: A picture is an <img> tag. Whether the browser initiates a request for the picture is based on the src attribute of <img>. Therefore, the key to implementing lazy loading is not to assign a value to the src of <img> before the picture enters the visible area. In this way, the browser will not send a request and will wait until the picture enters the visible area before assigning a value to the 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 image needs to be lazy loaded visible = $(this).offset().top - $(window).scrollTop(); // The distance between the image and the top if ((visible > 0) && (visible < $(window).height())) {// Determine whether the image is in the visible area visible = true;// The image is in the visible area } else { visible = false; // The image 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 window.onscroll = function(){ lazyload(imgs); } 2. Preloading Principle: Load images 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 user operations are reflected as quickly as possible. Several ways to implement preloading 1. CSS implementation Principle: Images can be preloaded onto an off-screen background using the CSS background property. As long as the paths to these images remain the same, the browser will use the preloaded (cached) images during the rendering process when they are called elsewhere in the web page. Simple, efficient, and no JavaScript required. #preload-01 { background: url(upload/2022/web/image-01.png) no-repeat -9999px -9999px; } #preload-02 { background: url(upload/2022/web/image-02.png) no-repeat -9999px -9999px; } #preload-03 { background: url(upload/2022/web/image-03.png) no-repeat -9999px -9999px; } 2. js preload images Principle: Preload by writing functions. Wrap the script in a function and use addLoadEvent() to delay the preload until the page has loaded. function preloader() { if (document.images) { var img1 = new Image(); var img2 = new Image(); var img3 = new Image(); img1.src = "upload/2022/web/image-001.gif"; img2.src = "upload/2022/web/image-002.gif"; img3.src = "upload/2022/web/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. Use ajax to implement preloading Principle: Use Ajax to implement image preloading method, using DOM, not only preloading images, but also preloading CSS, JavaScript and other related things window.onload = function() { setTimeout(function() { // XHR to request a JS and a CSS var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://domain.tld/preload.js'); xhr.send(''); xhr = new XMLHttpRequest(); xhr.open('GET', 'http://domain.tld/preload.css'); xhr.send(''); // preload image new Image().src = "upload/2022/web/preload.png"; }, 1000); }; The above code preloads "preload.js", "preload.css" and "preload.png". The 1000 millisecond timeout is to prevent the script from hanging and causing functional issues with normal pages. 3. Comparison between lazy loading and preloading 1. Concept Delayed loading is also called lazy loading: data loading is performed only when the data is really needed. 2. Difference
3. Significance The main purpose of lazy loading is to optimize front-end performance and reduce the number of requests or delay the number of requests. IV. References 【1】https://www.jb51.net/article/154930.htm This is the end of this article about the specific use of lazy loading and preloading in js. For more relevant content about lazy loading and preloading in js, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Writing and understanding of arrow functions and this in JS
>>: Example code of the spread operator and its application in JavaScript
Better-scroll scrolling principle As a parent con...
This is an enhanced version. The questions and SQ...
This article uses an example to illustrate the us...
At the beginning of the new year, I would like to...
The system environment is server2012 1. Download ...
Recently, when I was drawing an interface, I enco...
Key Points The CSS resize property allows you to ...
Table of contents 1. Basic Concepts of GTID 2. GT...
There is a big difference between the writing ord...
css3 background image related Compatibility: IE9+...
Table of contents Overview Form validation withou...
1. Favicon.cc To create ico icon websites online,...
Table of contents Overview Precautions 1. Usage 2...
Table of contents Overview 1. Acquisition and pro...
Are you still looking for a way to enable Hyper-v...