在动态插入jQuery库完成加载后执行我的jQuery脚本

我通过标签在页面上动态插入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); } })();