How do I insert a script tag in to the top/beginning of head tag?

ε祈祈猫儿з 提交于 2019-12-07 05:43:56

问题


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);

回答1:


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

head.insertBefore(script, head.firstChild);



回答2:


Get the firstChild of the <head>, and then use insertBefore.

This won't change the order scripts are loaded in though (since you'll be inserting it into the DOM after other scripts have been parsed), so this won't give any significate difference from just using appendChild




回答3:


document.head.insertBefore(script, document.head.firstElementChild);


来源:https://stackoverflow.com/questions/12979366/how-do-i-insert-a-script-tag-in-to-the-top-beginning-of-head-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!