简体   繁体   中英

Dynamically add JS code to head tag

I am trying to add a script to the head tag of my page. I am seeing the code that I am trying to add in the body tag but it doesn't show up in head tag.

$(document).load(function() {
   $('<script>console.log("hi");</' + 'script>').appendTo("head")
});

I see this being added in <body> but I dont see it in <head> .

I tried variations of append, appendTo and document.ready and document.load functions. None of those worked so far.

I went through cpuple of similar threads before I posted. I didn't seem to fix my issue

One thing you might need to do is escape the </ as <\\/

If its an inline script though maybe you can try just adding a setTimeout to it.

Try the following function:

(function (src) {
    var tagName = 'script', script = document.createElement(tagName);
    script.src = src;
    var elm = document.getElementsByTagName(tagName)[0];
    elm.parentNode.insertBefore(script, elm);
})('SCRIPT.SRC.HERE.js');

This will create a dynamic script tag and add it before the first script tag. Although it won't work in the way you want if you don't have any script tags inside your head . In this case, you could use the following function:

(function (src) {
    var tagName = 'script', script = document.createElement(tagName);
    script.src = src;
    var head = document.getElementsByTagName('head')[0];
    head.insertBefore(script, head.childNodes[0]);
})('SCRIPT.SRC.HERE.js');

This will directly get the first element inside your head tag and append the new script before it.

The document doesn't fire a "load" event - or if it does, it's a bubbled event from something else loading (like another script or image file). Try changing document to window :

http://jsfiddle.net/5bhmwyrx/3/

$(window).load(function() {
   var script = $('<script>console.log("hi");</' + 'script>').appendTo(document.head);
   console.log("Script was appended to", script[0].parentNode.nodeName);
   //-> Script was appended to HEAD
});

$(document).load(function() {
   console.log("You should never see this");
});

document.onload = function () {
    console.log("You should not see this in modern browsers");
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM