There are generally several ways to preload a picture
1.html tag or CSS load picture
It is obvious that we can use the IMG tag or the Background-image property of the tag to achieve preload of the picture. However, to avoid the initial loading of too many pictures affect the experience. It is generally best to load the document after rendering is complete (using window.onload, etc.).
2. Pre-loading for pure JS implementation
Kongchengji-code A pre-loading instance of the full implementation of a picture by JavaScript
function Preloadimages (arr) {
var newimages=[], Loadedimages=0
var postaction=function () {}// Added here is a postaction function
var arr= (typeof arr!= "Object")? [arr]: arr
function Imageloadpost () {
loadedimages++
if (loadedimages==arr.length) {
postaction ( Newimages)//loading complete use we call the Postaction function and pass the newimages array as parameters in
}
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 {//Here the Done method of returning a blank object is done
: function (f) {
Postaction=f | | postaction
}
}
}
The principle is to loop the creation of the image object, and set the src of the object to the specified picture, and then listen to the picture load complete onload = function () {imageloadpost ()}, which executes to imageloadpost when the picture is loaded. The original IE6 also has a problem: if the preloaded picture is already in memory, it will not start the Img.onload event again. But ie7+ has no problem. Other browsers are fine, so there is no compatibility problem with this img.onload listening event.
Pre-loading 3.Ajax implementation
Ajax requests are any data that can be requested, and pictures are no exception. Let's take a 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 ');
And the image of Ajax preload actual and pure JS pre-loading pictures like
But the explanation here is an AJAX load, and it's understandable that new image is an AJAX GET request.
The above is the entire content of this article, I hope you understand the JS picture preload help.