A variety of js image preload implementation to share

  • 2020-12-22 17:34:18
  • OfStack

There are generally several ways to preload images

1.html tag or css to load images

Obviously we can use the img tag or use the ES8en-ES9en attribute of the tag to preload the image. But in order not to load too many images for the first time to affect the experience. It is generally best to load after the document is rendered (using window. onload, etc.).

2. Pure js implements pre-loading

Empty city meter -Code notes the Javascript image of the full implementation of the pre-load of the pre-load example is


function preloadimages(arr){  
  var newimages=[], loadedimages=0
  var postaction=function(){} // Here we add 1 a postaction function 
  var arr=(typeof arr!="object")? [arr] : arr
  function imageloadpost(){
    loadedimages++
    if (loadedimages==arr.length){
      postaction(newimages) // Load finished with our call postaction Function and will newimages The array is passed in as a parameter 
    }
  }
  for (var i=0; i<arr.length; i++){
    newimages[i]=new Image()
    newimages[i].src=arr[i]
    newimages[i].onload=function(){
      imageloadpost()
    }
    newimages[i].onerror=function(){
      imageloadpost()
    }
  }
  return { // Return here 1 Of a blank object done methods 
    done:function(f){
      postaction=f || postaction
    }
  }
}

The principle is to loop to create the Image object, set src of the object as the specified image, and then listen to the image load complete onload = function(){imageloadpost()}, when the image load is completed, it will be executed to imageloadpost. It turns out IE6 has a problem: if the preloaded image is already in memory, the ES30en.onload event will not be triggered again. But there are no problems with IE7+. Other browsers also have no problems, so the above img.onload listening event is no longer compatible.

3.Ajax implements pre-loading

ajax requests are available for any data, and images are no exception. First look at js/css pre-loading


// 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(''); 

The image of ajax pre-loaded actual and pure js pre-loaded image 1


new Image().src = "http://domain.tld/preload.png"; 

ajax loading, new Image is ajax get request.

That's all for this article, and hopefully it will help you understand the pre-loading of js images.


Related articles: