在动态插入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); } })();
- 在FullCalendar dayClick上触发jQuery Qtip
- textarea关于输入问题
- 在`mousedown`事件期间添加新元素会阻止触发`click`事件?
- 拦截JavaScript卸载事件
- 更改后jQuery AutoComplete选择触发?
- 在“mousedown”中使用event.preventDefault()是否会阻止jquery中的“click”或“mouseup”事件?
- 从jQuery或vanilla javascript事件触发合成ExtJS事件
- 如何绑定到模糊和更改,但只在Jquery / Javascript中触发一次函数?
- 使用jQuery绑定AngularJS元素指令上的事件