Home > Web Front-end > JS Tutorial > body text

Implementation of JS preloading images

小云云
Release: 2018-03-26 15:35:19
Original
1793 people have browsed it


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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template