一旦条件满足,异步调用函数
Async call a function once condition is met?
我正在通过bookmarklet向页面注入jQuery和一些jQuery插件。插件必须在jQuery加载完成后启动。否则我将得到一个错误,"jQuery未定义"。所以我需要一个办法把它推迟到那个时候。
目前我使用setInterval。它继续循环,直到满足条件,然后创建下一个脚本。
函数调用
injectScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js');
injectScript('http://www.jnathanson.com/blog/client/jquery/heatcolor/jquery.heatcolor.0.0.1.pack.js', function(){return typeof jQuery != 'undefined'});
函数定义
function injectScript(src, dependency){
/* Description: creates a new script within the DOM */
/* Syntax: */
/* src */
/* contains a string to the link location of */
/* the script. */
/* dependency */
/* a function that returns true when all dependent */
/* scripts are finished loading. */
scriptLoad.total++;
dependency = dependency || function(){return true};
var depenLoop = setInterval(function(){ /* Wait for dependencies to finish loading, then create the script */
if(dependency()){
clearInterval(depenLoop);
var script = document.createElement('script');
script.onload = function(){ scriptLoad.ready++; }; /* onload must be set before src, otherwise src could */
script.src = src; /* finish early and onload would never fire. */
document.body.appendChild(script);
}/*end if*/
}, 100);/*loop*/
}/*end function*/
混乱,但这段代码可以工作。然而,我正在寻找一个更好的解决方案。有没有其他的方法来做到这一点,而不使用setInterval
和纯JS?
使用
<script src="jquery.js"></script>
<script>
$(function(){
// Code to execute after jQuery has loaded
});
</script>
</body>
放置<</p>
相关文章:
- 如何使用异步调用更改工厂的变量
- 使变量可用于不带闭包的异步调用
- 需要收集Javascript nodejs异步调用
- 如何使用jQuery等待来自回调的异步调用
- 使用模态库从嵌套的异步调用中生成javascript同步代码
- 在forEach内部进行异步调用
- jQuery没有指定异步调用级别async:false
- SPA异步调用在IE 11中不起作用
- Ember.js-模型find()方法中的异步调用
- Javascript/JQuery处理并发/异步调用和数据竞争
- 在异步调用返回之前隐藏页面
- ExtJs 处理异步调用
- ES6:在异步调用中使用生成器
- Angular js - 异步调用 $scope.users 后不更新模态值
- 在每个循环上完成异步调用,然后转到下一个节点 js
- 从异步调用返回数组,然后为数组的每个元素返回其他异步调用
- 使用 AngularJS 的异步调用
- 循环内部的Javascript异步调用
- 使用Canvas和ForEach处理异步调用
- JavaScript/promise,对sharepoint的多个异步调用