[英]Async call a function once condition is met?
I'm injecting jQuery and a few jQuery plugins into a page via a bookmarklet. 我通过书签将jQuery和一些jQuery插件注入页面。 The plugins must be started after jQuery is finished loading.
必须在jQuery完成加载后才能启动插件。 Otherwise I'll get an error, "jQuery is not defined".
否则,我将得到一个错误,“未定义jQuery”。 So I need a way to delay it until then.
因此,我需要一种将其延迟到那时的方法。
Currently I'm using setInterval. 目前,我正在使用setInterval。 It keeps looping until the condition is satisfied, then creates the next script.
它一直循环直到满足条件,然后创建下一个脚本。
Function Calls 函数调用
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 Definitions 功能定义
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*/
Messy, but this code works. 混乱,但是此代码有效。 However I'm looking for a better solution.
但是,我正在寻找更好的解决方案。 Is any other way to do this without using
setInterval
and with pure JS? 还有其他方法可以不使用
setInterval
和纯JS来做到这一点吗?
Use 采用
<script src="jquery.js"></script>
<script>
$(function(){
// Code to execute after jQuery has loaded
});
</script>
</body>
Place the <script> tags that include jQuery at the end of the document body, and then add the code for your plugins after it. 将包含jQuery的<script>标记放在文档主体的末尾,然后在其后添加插件代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.