JavaScript是多线程的吗? [英] Is JavaScript multithreaded?
问题描述
这是我的问题 - 我需要使用jQuery.getScript()动态下载几个脚本并执行某些 JavaScript 加载所有脚本后的代码,所以我的计划是做这样的事情:
Here's my issue - I need to dynamically download several scripts using jQuery.getScript() and execute certain JavaScript code after all the scripts were loaded, so my plan was to do something like this:
function GetScripts(scripts, callback)
{
var len = scripts.length
for (var i in scripts)
{
jQuery.getScript(scripts[i], function()
{
len --;
// executing callback function if this is the last script that loaded
if (len == 0)
callback()
})
}
}
如果我们假设这只能可靠地工作每个脚本的script.onload事件触发并按顺序和同步执行,因此当两个或多个事件处理程序检查(len == 0)并执行回调方法时,永远不会出现这种情况。
This will only work reliably if we assume that script.onload events for each script fire and execute sequentially and synchronously, so there would never be a situation when two or more of the event handlers would pass check for (len == 0) and execute callback method.
所以我的问题 - 这个假设是正确的,如果不是,那么实现我想要做的是什么?
So my question - is that assumption correct and if not, what's the way to achieve what I am trying to do?
推荐答案
不,JavaScript不是多线程。它是事件驱动的,你按顺序触发事件的假设(假设它们按顺序加载)就是你将看到的。您当前的实施似乎是正确的我相信jQuery的 .getScript()
会注入一个新的< script>
标记,这也应该强制它们加载正确的订单。
No, JavaScript is not multi-threaded. It is event driven and your assumption of the events firing sequentially (assuming they load sequentially) is what you will see. Your current implementation appears correct. I believe jQuery's .getScript()
injects a new <script>
tag, which should also force them to load in the correct order.
这篇关于JavaScript是多线程的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!