Web*_*ner 3 javascript jquery events javascript-events onload
我通过<script>标签在页面上动态插入jQuery库:
jq = document.createElement('script');
jq.setAttribute('src','//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
b.appendChild(jq);
Run Code Online (Sandbox Code Playgroud)
然后我有一些jQuery脚本需要在jQuery库加载完成后运行并准备好使用:
$(f).load(function() {
$(f).fadein(1000);
});
Run Code Online (Sandbox Code Playgroud)
如何让它等待jQuery加载?
Rob*_*b W 14
onload在要插入的脚本标记处指定事件:
function onLoad() {
$(f).load(function() {
$(f).fadein(1000);
});
}
jq = document.createElement('script');
jq.onload = onLoad; // <-- The magic
jq.src = '//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';
b.appendChild(jq);
Run Code Online (Sandbox Code Playgroud)
另一种方法是,如果无法控制脚本插入代码,则可以使用轮询器:
(function() {
function onLoad() { ... } // Code to be run
if ('jQuery' in window) onLoad();
else {
var t = setInterval(function() { // Run poller
if ('jQuery' in window) {
onLoad();
clearInterval(t); // Stop poller
}
}, 50);
}
})();
Run Code Online (Sandbox Code Playgroud)