简体   繁体   English

动态将JS代码添加到head标签

[英]Dynamically add JS code to head tag

I am trying to add a script to the head tag of my page. 我正在尝试将脚本添加到页面的head标签。 I am seeing the code that I am trying to add in the body tag but it doesn't show up in head tag. 我正在尝试在body标签中添加代码,但未在head标签中显示。

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

I see this being added in <body> but I dont see it in <head> . 我看到这是在<body>中添加的,但是我没有在<head>看到它。

I tried variations of append, appendTo and document.ready and document.load functions. 我尝试了append,appendTo和document.ready和document.load函数的变体。 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. 如果它是一个内联脚本,也许您可​​以尝试向其添加setTimeout。

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. 这将创建一个动态script标签,并将其添加到第一个script标签之前。 Although it won't work in the way you want if you don't have any script tags inside your head . 如果如果head没有任何script标签,它将无法以您希望的方式工作。 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. 这将直接获取head标记内的第一个元素,并在其之前附加新脚本。

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). document不会触发“加载”事件-否则,它是来自其他加载对象(例如另一个脚本或图像文件)的冒泡事件。 Try changing document to window : 尝试将document更改为window

http://jsfiddle.net/5bhmwyrx/3/ 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");
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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