如何将脚本标签插入头部标签的顶部/开头?

2022-01-22 00:00:00 append native javascript appendchild

我想在 head 标记中的所有其他脚本之前插入一个脚本标记.我将如何使用原生 javascript 做到这一点?

I want to insert a script tag before all the rest of the scripts in the head tag. How would I do that with native javascript?

<head>
    //INSERT SCRIPT HERE
     <script type="text/javascript" src="common.js"></script>
     <script type="text/javascript" src="omni-controls.js"></script>
</head>

当我使用它时,它只是附加在头标签中的所有标签之后.

When I use this, it just appends after all the tags in the head tag.

document.getElementsByTagName("head")[0].appendChild(script);

推荐答案

var head = document.getElementsByTagName("head")[0]

head.insertBefore(script, head.firstChild);

相关文章