Ale*_*akh 9 html javascript asynchronous
在async静态地声明我的javascript与动态相比有什么区别吗?
静态的
<html>
<head>
...
</head>
<body>
...
<div id='my-script-needs-me'></div>
<script type="text/javascript" src="https://foo.bar/myscript.js" async>
</script>
...
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
动态
<html>
<head>
...
</head>
<body>
...
<div id='my-script-needs-me'></div>
<script type="text/javascript">
var myScript = document.createElement("script");
myScript.src = 'https://foo.bar/myscript.js';
myScript.async = !0;
myScript.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(myScript);
</script>
...
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我注意到静态声明一个脚本让浏览器先检测到它并预加载(chrome + firefox).
我的目标是以一种async方式加载javascript,以便不阻止HTML呈现和其他脚本执行.Sametime,我希望它在下载后立即执行,记住它需要一个元素已经在DOM中.下载后,脚本将被执行并访问my-script-needs-mediv.一个限制,我不能改变脚本本身.
小智 2
支持异步参数,允许异步调用。
\n\n您描述的第二种方式允许您将 url 作为参数并绑定它。\n它也允许在加载脚本时使用回调来做一些事情。
\n\nlet scriptElement = document.createElement('script');\nlet url = `https://maps.googleapis.com/maps/api/js?key=${apiKey}`;//&libraries=geometry\n scriptElement.src = url;\n //Chargement de l'API Google\n scriptElement.onload = () => {\n //API charg\xc3\xa9e, on peut lancer l'initialisation du composant\n this._initializeMap();\n };\nRun Code Online (Sandbox Code Playgroud)\n\n我用它来加载 Google Maps API,它不是直接在 HTML 中,因此我可以在页面加载时修改 URL。加载 API 后,我会启动需要此 API 的治疗。
\n