Javascript 等待动态加载的脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7308908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Waiting for dynamically loaded script
提问by Aaron Digulla
In my page body, I need to insert this code as the result of an AJAX call:
在我的页面正文中,我需要插入此代码作为 AJAX 调用的结果:
<p>Loading jQuery</p>
<script type='text/javascript' src='scripts/jquery/core/jquery-1.4.4.js'></script>
<p>Using jQuery</p>
<script type='text/javascript'>
$.ajax({
...
});
</script>
I can't use $.load()
since the document has already loaded, so the event doesn't fire.
$.load()
由于文档已加载,因此我无法使用,因此不会触发该事件。
Is this safe? If not, how do I make sure the jquery script has loaded before my custom, generated code is executed.
这安全吗?如果没有,我如何确保在执行我的自定义生成的代码之前加载了 jquery 脚本。
采纳答案by jAndy
It is pretty safe. Historically, <script>
tags are full blocking, hence the second <script>
tag can't get encountered befored the former has finished parsing/excuting. Only problem might be that "modern" browsers tend to load scripts asynchronously and deferred. So to make sure order is correct, use it like this:
这是相当安全的。从历史上看,<script>
标签是完全阻塞的,因此<script>
在前者完成解析/执行之前无法遇到第二个标签。唯一的问题可能是“现代”浏览器倾向于异步和延迟加载脚本。因此,为了确保顺序正确,请像这样使用它:
<p>Loading jQuery</p>
<script type='text/javascript' async=false defer=false src='scripts/jquery/core/jquery-1.4.4.js'></script>
<p>Using jQuery</p>
<script type='text/javascript'>
$.ajax({
...
});
</script>
However, it's probably a better idea it use dynamic script tag insertion instead of pushing this as HTML string into the DOM. Would be the same story
但是,使用动态脚本标记插入而不是将其作为 HTML 字符串推送到 DOM 中可能是一个更好的主意。会是同一个故事
var scr = document.createElement('script'),
head = document.head || document.getElementsByTagName('head')[0];
scr.src = 'scripts/jquery/core/jquery-1.4.4.js';
scr.async = false; // optionally
head.insertBefore(scr, head.firstChild);
回答by Rob Fox
Add an ID to your script file so you can query it.
将 ID 添加到您的脚本文件,以便您可以查询它。
<script id="hljs" async src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.0.0/highlight.min.js"></script>
Then add a load listener to it in JavaScript
然后在 JavaScript 中为其添加一个加载侦听器
<script>
var script = document.querySelector('#hljs');
script.addEventListener('load', function() {
hljs.initHighlightingOnLoad();
});
</script>
回答by Umur Kontac?
There is also new feature in jQuery 1.6
. It is called jQuery.holdReady()
. It is actually self explanatory; when you call jQuery.holdReady(true)
, ready
event is not fired until you call jQuery.holdReady(false)
. Setting this to false will not automatically fire a ready event, it just removes the hold.
中还有一个新功能jQuery 1.6
。它被称为jQuery.holdReady()
。它实际上是不言自明的;当你打电话时jQuery.holdReady(true)
,ready
事件不会被触发,直到你打电话jQuery.holdReady(false)
。将此设置为 false 不会自动触发就绪事件,它只会删除保留。
Here is a non-blocking example of loading a script taken from the documentation:
这是加载从文档中获取的脚本的非阻塞示例:
$.holdReady(true);
$.getScript("myplugin.js", function() {
$.holdReady(false);
});
See http://api.jquery.com/jQuery.holdReady/for more information
有关更多信息,请参阅http://api.jquery.com/jQuery.holdReady/
回答by Luke Robertson
const jsScript = document.createElement('script')
jsScript.src =
'https://coolJavascript.js'
document.body.appendChild(jsScript)
jsScript.addEventListener('load', () => {
doSomethingNow()
})
Will load after the script is dynamically added
动态添加脚本后才会加载
回答by austinbv
$.ajax and $.load are the same thing. You can use either. If you put $.load in a script tag on the page it will fire when it loads just like $.ajax().
$.ajax 和 $.load 是一回事。你可以使用。如果您将 $.load 放在页面上的脚本标记中,它将在加载时触发,就像 $.ajax() 一样。
When it comes to waiting for a script to fire before you do something what Tomalak said is kinda true. The exception is asynchronous calls. Javascript will make an AJAX call then continue running the script and when the AJAX call responds it will run the success/fail depending on what you tell it to do.
当谈到在你做某事之前等待脚本触发时,托马拉克说的有点真实。异步调用除外。Javascript 将进行 AJAX 调用,然后继续运行脚本,当 AJAX 调用响应时,它将根据您告诉它执行的操作运行成功/失败。
Now say you want your JS to wait for the return, with a single call it's pretty easy just wrap every thing in the success callback, or you could do it the cool way and use $.deferred. This allows you to make a bunch of ajax calls or one and then run some code only after the finish.
现在假设您希望您的 JS 等待返回,只需一次调用就可以很容易地将所有内容包装在成功回调中,或者您可以使用很酷的方式并使用 $.deferred。这允许您进行一堆 ajax 调用或一个,然后仅在完成后运行一些代码。
$.when & $.then are probably the best for this situation.
$.when 和 $.then 可能最适合这种情况。
Any way what your are doing is safe.
无论如何,您所做的都是安全的。