Javascript在加载异步资源后运行内联脚本 [英] Javascript run inline script after load async resources
问题描述
当我通过优化器测试页面时,它建议我对我使用的所有CDN源使用async。
when I test page by optimizer, it suggest me use async for all CDN sources what I use.
要运行我使用的任何脚本
To run any script I use
(function(){})();
我也用javascript代码按内联脚本
标签。如何运行内联脚本,如:
I use also javascript code by inline script
tags. How to run inline script like:
<script>
(function(){
jQuery.foundation();
ReactDOM.render(<App />,document.querySelector('#app'));
});
</script>
?我已经尝试过异步标记,但它不起作用。我有错误,不存在由异步加载的库。
? I've been tried async for tag but it doesn't works. I have error that doesn't exists libraries loaded by async.
推荐答案
将代码包装在:
(function () {
})();
...不会延迟执行。要延迟脚本直到加载资源,请等待窗口加载
事件:
... does not delay its execution. To delay your script until resources have been loaded, wait to the window load
event:
加载事件在结束时触发文件加载过程。此时,文档中的所有对象都在DOM中,所有图像 脚本 ,链接和子帧都已完成加载。
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
这是一个用< script async>
元素加载jQuery的示例,并显示通过内联脚本的jQuery版本:
Here is an example that loads jQuery with a <script async>
element, and shows the jQuery version via the inline script:
window.addEventListener('load', function () {
console.log(jQuery.fn.jquery);
});
<script async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
在特定 <$时捕获事件c $ c> async 脚本已加载,您可以收听自己的加载
ev ENT。为了实现这一目标,如果您将 id
提供给您感兴趣的脚本
元素,这可能是最简单的,并且确保内联代码在它之后:
To capture the event when a particular async
script has been loaded, you could listen to its own load
event. For that to work it is probably the easiest if you give an id
to the script
element of your interest, and make sure the inline code comes after it:
jq.addEventListener('load', function () {
console.log(jQuery.fn.jquery);
});
<script id="jq" async src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
请注意 async
(和 defer
)属性对内联脚本没有影响:
Note that the async
(and defer
) attributes have no effect on inline scripts:
defer
和async
属性如果src
属性不存在,则不得指定s。
The
defer
andasync
attributes must not be specified if thesrc
attribute is not present.
他们仅对具有 src
属性的脚本
元素产生影响。
They only have an effect on script
elements that have the src
attribute.
这篇关于Javascript在加载异步资源后运行内联脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!