javascript将defer或async属性添加到动态生成的

javascript将defer或async属性添加到动态生成的

本文介绍了通过javascript将defer或async属性添加到动态生成的脚本标记中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在动态地将脚本标记放到我的页面的DOM中,如下所示:

I am dynamically putting a script tag to the DOM of my page like this:

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

这应该产生如下内容:

<script src="https://www.youtube.com/iframe_api"></script>

我只想对此脚本标记进行延迟或异步:

I just want to put in a defer or async to this script tag like this:

<script src="https://www.youtube.com/iframe_api" defer async></script>

那么如何使用javascript进行此操作?

So how do I do this using javascript?

推荐答案

无需在脚本标记中添加 async ,因为该属性是并且脚本将加载异步,除非告诉不要。

There's no need to add async to your script tag, since that attribute is enabled by default and scripts will load asynchronously unless told not to.

至于推迟,就像更改 src一样JavaScript中的属性,你也可以这样启用:

As for defer, just as you change the src attribute in JavaScript, you can also enable that one like so:

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
tag.defer = true;
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

或者,您可以使用。

Alternatively, you can use setAttribute() for this.

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
tag.setAttribute('defer','');
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

这篇关于通过javascript将defer或async属性添加到动态生成的脚本标记中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 17:04