document.createElement('script')... 使用一个回调添加两个脚本
我需要添加原型,然后添加 scriptaculous 并在它们都完成加载时获取回调。我目前正在加载原型,如下所示:
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js";
script.onload = script.onreadystatechange = callback;
document.body.appendChild( script );
我可以通过链接回调来完成此操作,但这似乎是不好的做法(当我需要加载更多脚本时,我不想要 20 个回调方法的愚蠢链)。有想法吗?
I need to add prototype and then add scriptaculous and get a callback when they are both done loading. I am currently loading prototype like so:
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js";
script.onload = script.onreadystatechange = callback;
document.body.appendChild( script );
I could do this by chaining the callbacks, but that seems like poor practice ( I don't want a silly chain of 20 callback methods when I need to load more scripts). Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议你使用一些小型装载机,它可以链接并为你做一些事情。例如,像这样:
此脚本应该帮助您构建脚本标签并在加载所有文件时调用回调。调用非常简单:
希望这会有所帮助
I propose you to use some small loader which will chain and do stuff for you. For example like this one:
This script should help you to build the script tags and call your callback when all files are loaded. Invoke is pretty easy:
Hope this will help
由于 Internet Explorer 中的错误,nemisj 的递归加载程序在 IE 中无法正常工作。可以通过在递归调用上设置延迟来解决,例如:
这个小技巧做到了,并且通常是 IE 中的解决方案,当出现无法解释的问题时,这种情况太常见了。
Because of a bug in Internet Explorer the recursive loader program from nemisj is not working correct in IE. Can be solved by setting a delay on the recursive call like:
This small hack does it, and often is the solution in IE, when an unexplainable problem occurs, which is too often.
由于 scriptaculous 需要原型,因此您必须使用任何加载这些脚本的方法来链接侦听器。
有各种脚本加载器可用于尽可能快地并行加载脚本,例如 LABjs,但没有一个有帮助在这种情况下。
如果您最终要加载 10-20 个脚本,我建议您使用 等工具预先组合这些脚本组合器。
Since scriptaculous requires prototype, you will have to chain the listeners, with whatever method you use to load these scripts.
There are various script loaders available to load scripts in parallel, as fast as possible, e.g. LABjs, but none is going to help much in this scenario.
If you end up having 10-20 scripts to load, I would recommend combining the scripts beforehand, using a tool such as a Combiner.
您可以承诺 脚本的
.onload 和
.onerror
回调,然后使用Promise.all
等待所有 Promise 解析,然后再继续执行依赖于这些脚本的操作。这是一个例子:
You can promisify the script's
.onload
and.onerror
callbacks, then usePromise.all
to wait for all of the promises to resolve before continuing with execution that is dependent on these scripts.Here's an example: