Last active
October 27, 2015 11:32
-
-
Save libo1106/a71294d4d252f07ec68c to your computer and use it in GitHub Desktop.
当页面中全部img都onload后执行
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 页面中全部img都onload后执行 | |
* @param callback | |
* @param opts.timeout 超时执行 | |
*/ | |
function imgAllLoadCall(callback, opts) { | |
var imagesCount = 0; // 待加载img计数 | |
var successCount = 0; // 已加载img计数 | |
var images = document.images; // document中所有img的数组集合 | |
var timeout = opts.timeout || 1000; // 超时,默认为1000毫秒,当1000毫秒后,立即执行回调 | |
var hasCalled = false; // 回调是否已执行 | |
var timer; // 定时器 | |
for (var i = 0; i < images.length; i++) { | |
// 过滤没有src和已经加载完成的图片 | |
if (!img.src || img.complete) { | |
return; | |
} | |
imagesCount++; | |
img.addEventListener('load', _onLoadHandler, false); | |
} | |
// 当页面中不存在待加载的图片时,立即执行回调 | |
if (imagesCount === 0) { | |
timeout = 0; | |
} | |
// 设定超时后执行回调 | |
timer = setTimeout(_onceCallBack, timeout); | |
/** | |
* 图片load事件 | |
* @private | |
*/ | |
function _onLoadHandler() { | |
successCount++; | |
if (successCount === imagesCount) { | |
clearTimeout(timer); | |
_onceCallBack(); | |
} | |
} | |
/** | |
* 执行一次性回调 | |
* @private | |
*/ | |
function _onceCallBack() { | |
if (hasCalled) { | |
return; | |
} | |
hasCalled = true; | |
callback(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment