Home >Web Front-end >JS Tutorial >Implementation of JS preloading images
This article mainly shares with you the implementation of JS preloading images, hoping to help everyone.
Requirement: Click the button in the project to realize the function of switching background images.
Problem: When switching the background-image attribute of css, if the image is loaded first and then displayed, there will be a momentary blank period.
Solution: Preload the background image in advance
First use the Image() constructor to create an off-screen image object, and then set the src attribute of the object to the URL. Since the image element is not added to the document, it is invisible, but the browser will still load the image and Cache it.
function preloadImg(url){ var imageObj = new Image() imageObj.src=url }var aImgUrlList = ['image1.png', 'image2.png']for (var i of aImgUrlList) preloadImg(i)
Related recommendations:
js preloading image method summary_javascript skills
The above is the detailed content of Implementation of JS preloading images. For more information, please follow other related articles on the PHP Chinese website!