
Javascript delay loading images to improve web page display speed
Large images in web page usually affect the display speed and thus the user experience. Therefore, it is necessary to delay loading it. If there are many large images, you need to load them by scrolling to save server resources. There are not many images and the images that must be displayed can be delayed to load a little to improve the user experience.
How to delay loading images? This requires javascript to complete. After the webpage is loaded or in a few seconds, execute a piece of javascript code to load the image. Let's see how to write this javascript code for delayed loading of images. There are two methods.
Javascript delay loading images to improve web page display speed
Method 1: Assign the image to the specified element
After the web page is loaded, assign the large image to be loaded to the element that needs to display the image. The code is as follows:
Html code:
<div id="divImages"></div>
Javascript code:
function DelayloadingImages() {
var imgDiv = document.getElementById("divImages");
imgDiv.innerHTML = "<img src='/images/loadimg.jpg' />";
}
setTimeout("DelayloadingImages()", 3000);
The above code is to load the image in 3 seconds after the webpage is loaded. You need to put this code behind html elements in the webpage. If the javascript code is placed in the file, you need to quote it behind html elements in the webpage.
Method 2: Load a blank small image first and then the big images
This method needs to load a blank small image first, but it is conducive to crawling by search engine spiders, the code is as follows:
Html code:
<div id="divImages">
<img tsrc="Big image 1 address" src="Blank small image address" />
<img tsrc="Big image 2 address" src="Blank small image address" />
</div>
Javascript code:
function DelayloadingImages() {
var imgDiv = document.getElementById("divImages");
var images = imgDiv.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
images[i].setAttribute("src", images[i].getAttribute("tsrc"));
}
}
setTimeout("DelayloadingImages()", 3000);
The above code must also be placed behind html elements in the webpage and executed after the webpage is loaded. If it is placed in the javascript file, it needs to be quoted after html elements in the webpage.
-
Related Reading
- Javascript multidimensional array (create, add and r
- Remove text after clicking in the textbox and then d
- Javascript get referrer url(previous page url), curr
- Javascript get current url, domain from url, relativ
- Javascript convert hex to decimal, binary to hex, oc
- Remove html element javascript by their parent or cl
- Javascript get all input elements in form and all im
- Javascript create element(div,li,img,span) dynamical
- Mod operator and rounding off numbers in javascript
- Javascript focus textbox when the web page is loaded
- Javascript input checked automatically with onblue
- Javascript select onchange get value, with dropdownl