我在页面底部有这种延迟加载脚本。它加载脚本确定,但现在缺少旧的jquery onload事件。
var dfLoadStatus = 0;
var dfLoadFiles = [
["//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"],
["//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js",
"/js/jquery.unveil.js",
"/scripts/js/jquery.cookie.js"]
];
function downloadJSAtOnload() {
if (!dfLoadFiles.length) return;
var dfGroup = dfLoadFiles.shift();
dfLoadStatus = 0;
for (var i = 0; i < dfGroup.length; i++) {
dfLoadStatus++;
var element = document.createElement('script');
element.src = dfGroup[i];
element.onload = element.onreadystatechange = function() {
if (!this.readyState || this.readyState == 'complete') {
dfLoadStatus--;
if (dfLoadStatus==0) downloadJSAtOnload();
}
};
document.body.appendChild(element);
}
}
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
在转移到这个延迟加载之前,我曾经在jquery加载后使用了很多这样的脚本:
$(document).ready(function() {
$("img").unveil(200);
});
如何为该jquery函数创建替换函数/事件,该函数检测何时加载了所有这些脚本,或者至少加载了jquery?
答案 0 :(得分:1)
我的浏览器正在缓存该文件,因此旧代码对我有用。我重写了它,现在它适合我。
<强>的JavaScript 强>
var dfIndex = 0;
var dfLoadFiles =[
"//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js",
"//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js",
"//cdn.rawgit.com/luis-almeida/unveil/master/jquery.unveil.js",
"//cdn.rawgit.com/carhartl/jquery-cookie/master/src/jquery.cookie.js"];
function downloadJavasSript(){
loadJavaScript(dfLoadFiles[dfIndex]);
}
function loadJavaScript(file,callback){
var head=document.getElementsByTagName("head")[0];
var script=document.createElement('script');
script.src=file;
script.type='text/javascript';
//real browsers
script.onload=isJavaScriptLoaded;
//Internet explorer
script.onreadystatechange = function() {
if (this.readyState == 'complete') {
isJavaScriptLoaded();
}
};
head.appendChild(script);
}
function isJavaScriptLoaded(e){
dfIndex++;
if (dfIndex === dfLoadFiles.length){
pageLoaded();
} else {
loadJavaScript(dfLoadFiles[dfIndex]);
}
}
function pageLoaded(){
console.log('page loaded');
$("img").unveil();
}
if (window.addEventListener)
window.addEventListener("load", downloadJavasSript, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJavasSript);
else window.onload = downloadJavasSript;