[英]Execute my jQuery script after dynamically inserted jQuery library has finished loading
我通過<script>
標簽在頁面上動態插入 jQuery 庫:
jq = document.createElement('script');
jq.setAttribute('src','//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js');
b.appendChild(jq);
然后我有一些 jQuery 腳本需要在 jQuery 庫完成加載並准備使用后運行:
$(f).load(function() {
$(f).fadein(1000);
});
我怎樣才能讓它等待 jQuery 加載?
在要插入的腳本標簽處指定一個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);
另一種方式,如果無法控制腳本插入代碼,可以使用輪詢器:
(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);
}
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.