Some large external resources will cause the page to load slowly. At this time, the loading effect is usually added; what is implemented here is the loading effect based on the percentage of the image loading progress
1. onload onerror
It is recommended to use this method. After the image is loaded successfully, the onload event will be triggered. Even if there is a cache, as long as the image address is requested again, it will be triggered. onload event; failure to load the image will trigger the onerror event. This method has good compatibility and is recommended. 2. imgObj.onreadystatechange
Some browsers support this method. According to readState === 'complete', you can determine whether the image is loaded.
Tested:
Chrome and Firefox will not trigger this event
IE Edge version will not trigger this event
IE 10 9 will trigger this event Event; lower versions have not been tested
so it is not recommended to use
3. imgObj.complete
The complete attribute can determine whether the image is loaded. However, different browsers handle complete inconsistently:
If the picture resource is normal, the picture is loaded successfully. All browsers change complete from false to true;
But if the picture resource is abnormal, the picture Chrome and Firefox change from false to true after loading failure; but IE will always be false
, so this method is not recommended.
Image resource loading progress
document.addEventListener('DOMContentLoaded', function(){ var imgs = document.querySelectorAll('img'), //所有图片资源 show = 0, //百分比 num = 0; //加载完成的个数 var all = imgs.length; [].slice.call(imgs).forEach(function(element,index){ //不管是否加载成功,都num+1 element.addEventListener('load',function(){ num++; show = Math.floor(100*num/all); }) element.addEventListener('error',function(){ num++; show = Math.floor(100*num/all); }) }) })
After all
pages are loaded, hide the mask to achieve a more friendly loading effect
window.onload = function(){ document.querySelector('.mask').classList.add('hide'); }
The above is the detailed content of Determine image loading status and achieve percentage effect loading. For more information, please follow other related articles on the PHP Chinese website!