First, define
preload pictures are a good way to improve the user experience, load the user's desired picture in advance, ensure the picture fast, seamless release, so that users in the browser site to get a better user experience. Often used in picture galleries and other applications.
[note] loading a picture together with the rest of the page increases the overall load time of the page, so it's more appropriate to use window.onload if you use instant loading.
Two ideas
1, using a background image
Pre-loading a background picture using a page useless element
<style> body{margin:0;} img{width:100px;
height:100px;
} ul{margin:0;
padding:0;
List-style:none;
}. list li{height:0;
width:0;
</style>
2. Use image ()
Create tag with new image () or document.createelement (' img ') and load the picture by SRC assignment statement
<style>
body{
margin:0;
}
img{
width:100px;
height:100px;
}
</style>
Iii. the onload incident
the OnLoad event can be used to know exactly whether the picture is actually loaded, and may perform a series of operations on the image, such as getting the actual width and index of the current picture.
[Note 1] The SRC assignment statement for the picture must be placed behind the onload event of the picture. Otherwise, the picture may have finished loading, but the event binding has not been completed
<button> load Picture </button>
<script>
var obtn = document.getelementsbytagname (' button ') [0];
Obtn.onclick = function () {
preloadimg (' img/test.png ');
}
function preloadimg (URL) {
var oimg = document.createelement (' img ');
In the native environment, Ie8-browser under the Oimg onload event placed behind SRC will not be able to load the picture
oimg.src = URL;
Oimg.onload = function () {
document.body.appendChild (oimg);
Oimg.onload = null;
oimg = null;
}
}
</script>
[Note 2] The OnLoad property of the image object refers to an anonymous function object, and the anonymous function references the image object through its scope, which causes a memory leak in the IE6, so the circular reference should be lifted.
"Recursive notation"
Consider the more refined writing of onerror
Loop notation
The
wants this article to help you with your JavaScript programming.