Home  >  Article  >  Web Front-end  >  Implementation of JS preloading images

Implementation of JS preloading images

小云云
小云云Original
2018-03-26 15:35:191747browse


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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn