如何通过javascript将类型属性注入到所有脚本标记中 [英] How to inject type attribute into all script tags via javascript
问题描述
我想知道如何查询所有脚本标记并设置一个随机属性。我试过的东西不行:
document.getElementsByTagName(script)[0] .setAttribute(data-foo ,酒吧);
它只匹配第一个脚本标记。 (不需要jQuery,我喜欢它,但不是现在,它也需要跨浏览器,所以 querySelectorAll
将不起作用)。
编辑:
好吧,事实证明,纯粹的JavaScript查询选择器只会在加载时选择它们(正如Kolink指出的那样并解释系统)。所以我必须在其他脚本标签之后添加脚本。
一种可能性是让您的其他脚本使用 document.write
。
这是一个经典的案例,其中 document.write
非常有用。
//在main / powerhouse
//脚本源列表
var scripts = [script1.js, (var i = 0; i< scripts.length; i ++)
document.write('< scr','script2.js,script3.js]
ipt type =text / javascriptsrc =',scripts [i],'>< / scr','ipt>');
现在脚本会写在当前运行的脚本之后,并按预期同步加载。 / p>
I want to know how to query ALL script tags and set a random attribute. What I have tried does not work:
document.getElementsByTagName("script")[0].setAttribute("data-foo", "bar");
It only matches the first script tag. (No jQuery please. I love it, but not now. It also needs to be cross-browser so querySelectorAll
won't work).
Edit:
Okay, so as it turns out, pure-JavaScript query selectors only select things as they're loaded (As Kolink pointed out and thesystem explained). So I have to add the script which set's attributes after the other script tags.
One possibility would be to have your other scripts written dynamically to the page using document.write
.
This is a classic case where document.write
is very useful.
// In main/powerhouse
// list of script sources
var scripts = ["script1.js", "script2.js", "script3.js"]
for (var i = 0; i < scripts.length; i++)
document.write('<scr', 'ipt type="text/javascript" src="', scripts[i], '"></scr', 'ipt>');
Now the scripts will be written after the current running script, and will be loaded synchronously as expected.
这篇关于如何通过javascript将类型属性注入到所有脚本标记中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!