简体   繁体   English

如何将 DOM 元素脚本添加到 head 部分?

[英]How to add DOM element script to head section?

I want to add DOM element to head section of HTML.我想将 DOM 元素添加到 HTML 的 head 部分。 jQuery does not allow adding DOM element script to the head section and they execute instead, Reference . jQuery 不允许将 DOM 元素脚本添加到 head 部分,而是执行Reference

I want to add script tags and write a script within <head> section.我想添加script标签并在<head>部分中编写脚本。

var script = '<script type="text/javascript"> //function </script>'
$('head').append(script);

Something like this with functions.像这样的功能。 I tried jQuery and javascript\, but it does not work.我尝试了 jQuery 和 javascript\,但它不起作用。

Please tell me how to add and write script to head by jQuery or javascript.请告诉我如何通过 jQuery 或 javascript 添加和编写script

I tired the javascript to add DOM element, but it does not work with .innerHTML() to write to head.我厌倦了 javascript 添加 DOM 元素,但它不适用于.innerHTML()写入头部。 I am using jQuery 2.0.3 and jQuery UI 1.10.3.我正在使用 jQuery 2.0.3 和 jQuery UI 1.10.3。

I want to add base64 encoded script to head section.我想将 base64 编码脚本添加到 head 部分。 I use base64 decoder js like this to decode the javascript and then put on the head section.我使用这样的base64解码器js来解码javascript,然后放在头部。

//Edited //已编辑
It will be这将是

$.getScript('base64.js');
var encoded = "YWxlcnQoImhpIik7DQo="; //More text
var decoded = decodeString(encoded);
var script = '<script type="text/javascript">' +decoded + '</script>';
$('head').append(script);

To fit an encoded script and the addition in one javascript file.将编码脚本和添加内容放入一个 javascript 文件中。 I want to use base64.js or some other decoder javascript files for browsers does not accept atob() .我想使用base64.js或其他一些用于浏览器的解码器 javascript 文件不接受atob()

try this尝试这个

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'url';    

document.head.appendChild(script);

If injecting multiple script tags in the head like this with mix of local and remote script files a situation may arise where the local scripts that are dependent on external scripts (such as loading jQuery from googleapis) will have errors because the external scripts may not be loaded before the local ones are.如果像这样在头部注入多个脚本标签并混合本地和远程脚本文件,则可能会出现依赖外部脚本的本地脚本(例如从 googleapis 加载 jQuery)会出现错误的情况,因为外部脚本可能不是在本地加载之前加载。

So something like this would have a problem: ("jQuery is not defined" in jquery.some-plugin.js).所以这样的事情会有一个问题:(jquery.some-plugin.js 中的“jQuery is not defined”)。

var head = document.getElementsByTagName('head')[0];

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js";
head.appendChild(script);

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "/jquery.some-plugin.js";
head.appendChild(script);

Of course this situation is what the .onload() is for, but if multiple scripts are being loaded that can be cumbersome.当然,这种情况是 .onload() 的用途,但是如果要加载多个脚本,这可能会很麻烦。

As a resolution to this situation, I put together this function that will keep a queue of scripts to be loaded, loading each subsequent item after the previous finishes, and returns a Promise that resolves when the script (or the last script in the queue if no parameter) is done loading.作为对这种情况的解决方案,我将这个函数放在一起,该函数将保留要加载的脚本队列,在前一个完成后加载每个后续项目,并返回一个 Promise,当脚本(或队列中的最后一个脚本,如果无参数)完成加载。

load_script = function(src) {
    // Initialize scripts queue
    if( load_script.scripts === undefined ) {
        load_script.scripts = [];
        load_script.index = -1;
        load_script.loading = false;
        load_script.next = function() {
            if( load_script.loading ) return;

            // Load the next queue item
            load_script.loading = true;
            var item = load_script.scripts[++load_script.index];
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = item.src;
            // When complete, start next item in queue and resolve this item's promise
            script.onload = () => {
                load_script.loading = false;
                if( load_script.index < load_script.scripts.length - 1 ) load_script.next();
                item.resolve();
            };
            head.appendChild(script);
        };
    };

    // Adding a script to the queue
    if( src ) {
        // Check if already added
        for(var i=0; i < load_script.scripts.length; i++) {
            if( load_script.scripts[i].src == src ) return load_script.scripts[i].promise;
        }
        // Add to the queue
        var item = { src: src };
        item.promise = new Promise(resolve => {item.resolve = resolve;});
        load_script.scripts.push(item);
        load_script.next();
    }

    // Return the promise of the last queue item
    return load_script.scripts[ load_script.scripts.length - 1 ].promise;
};

With this adding scripts in order ensuring the previous are done before staring the next can be done like...有了这个添加脚本,以确保在盯着下一个之前完成前一个可以像......

["https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js",
 "/jquery.some-plugin.js",
 "/dependant-on-plugin.js",
].forEach(load_script);

Or load the script and use the return Promise to do work when it's complete...或者加载脚本并在完成后使用 return Promise 来完成工作......

load_script("some-script.js")
.then(function() {
    /* some-script.js is done loading */
});

try out ::试用 ::

 var script = document.createElement("script"); script.type="text/javascript"; script.innerHTML="alert('Hi!');"; document.getElementsByTagName('head')[0].appendChild(script);

As per the author, they want to create a script in the head, not a link to a script file.根据作者的说法,他们想在头部创建一个脚本,而不是指向脚本文件的链接。 Also, to avoid complications from jQuery (which provides little useful functionality in this case), vanilla javascript is likely the better option.此外,为了避免 jQuery 的复杂性(在这种情况下它几乎没有提供有用的功能),vanilla javascript 可能是更好的选择。

That may possibly be done as such:这可能会这样做:

var script = document.createTextNode("<script>alert('Hi!');</script>");   
document.getElementsByTagName('head')[0].appendChild(script);

Some clarification to those who may be confused on why this works: All code in the webpage is text.向那些可能对为什么会这样工作感到困惑的人进行一些澄清:网页中的所有代码都是文本。 Text is the most fundamental type in a web page.文本是网页中最基本的类型。 The browser simply starts processing through the text, following its rules, until it reaches the end (this includes loopbacks, recursion, etc.)浏览器简单地开始处理文本,遵循它的规则,直到它到达末尾(这包括环回、递归等)

For this to work, the script that makes this tag must also be in the header.为此,制作此标签的脚本必须在标题中。 The browser, when processing, will hit this code before reaching the end of the header, append the script you want onto the header, and then reach it later as it continues to process.浏览器在处理时会在到达标头末尾之前点击此代码,将您想要的脚本附加到标头上,然后在继续处理时到达它。 If you had a reliable end footer, you could change out 'head' for 'footer' or similar, but considering the most reliable across sites that have scripts is the existence of the header tag, that makes it the most useful option in this case.如果您有可靠的结束页脚,您可以将 'head' 更改为 'footer' 或类似内容,但考虑到具有脚本的站点中最可靠的是 header 标签的存在,这使得它在这种情况下成为最有用的选项.

Best solution I've found:我发现的最佳解决方案:

AppendToHead('script', 'alert("hii"); ');
//or
AppendToHead('script', 'http://example.com/script.js');
//or
AppendToHead('style', '#myDiv{color:red;} ');
//or
AppendToHead('style', 'http://example.com/style.css');

function AppendToHead(elemntType, content) {
  // detect whether provided content is "link" (instead of inline codes)
  var Is_Link = content.split(/\r\n|\r|\n/).length <= 1 && content.indexOf("//") > -1 && content.indexOf(" ") <= -1;
  if (Is_Link) {
    if (elemntType == 'script') {
      var x = document.createElement('script');
      x.id = id;
      x.src = content;
      x.type = 'text/javascript';
    } else if (elemntType == 'style') {
      var x = document.createElement('link');
      x.id = id;
      x.href = content;
      x.type = 'text/css';
      x.rel = 'stylesheet';
    }
  } else {
    var x = document.createElement(elemntType);
    if (elemntType == 'script') {
      x.type = 'text/javascript';
      x.innerHTML = content;
    } else if (elemntType == 'style') {
      x.type = 'text/css';
      if (x.styleSheet) {
        x.styleSheet.cssText = content;
      } else {
        x.appendChild(document.createTextNode(content));
      }
    }
  }
  //append in head
  (document.head || document.getElementsByTagName('head')[0]).appendChild(x);
}
var script = $('<script type="text/javascript">// function </script>')
document.getElementsByTagName("head")[0].appendChild(script[0])

But in that case script will not be executed and functions will be not accessible in global namespase.但在这种情况下,脚本将不会被执行,并且函数将无法在全局命名空间中访问。 To use code in <script> you need do as in you question要在<script>中使用代码,您需要按照您的问题进行操作

$('head').append(script);

This is an old question, and I know its asking specifically about adding a script tag into the head, however based on the OPs explanation they actually just intend to execute some JS code which has been obtained via some other JS function.这是一个老问题,我知道它专门询问如何在头部添加一个脚本标签,但是根据 OPs 的解释,他们实际上只是打算执行一些通过其他 JS 函数获得的 JS 代码。

This is much simpler than adding a script tag into the page.这比在页面中添加脚本标签要简单得多。

Simply:简单地:

eval(decoded);

Eval will execute a string of JS in-line, without any need to add it to the DOM at all. Eval 会直接执行一个 JS 字符串,根本不需要将它添加到 DOM 中。

I don't think there's ever really a need to add an in-line script tag to the DOM after page load.我认为在页面加载后不需要向 DOM 添加内联脚本标记。

More info here: http://www.w3schools.com/jsref/jsref_eval.asp更多信息在这里: http ://www.w3schools.com/jsref/jsref_eval.asp

you could do:你可以这样做:

var scriptTag = document.createElement("script");
scriptTag.type = "text/javascript";
scriptTag.src = "script_source_here";
(document.getElementsByTagName("head")[0] || document.documentElement ).appendChild(scriptTag);

I use PHP as my serverside language, so the example i will write in it - but i'm sure there is a method in your server side as well.我使用 PHP 作为我的服务器端语言,所以我将用它编写示例 - 但我确信您的服务器端也有一个方法。

Just have your serverside language add it from a variable.只需让您的服务器端语言从变量中添加它。 w/ php something like that would go as follows. w/php 类似的东西会如下所示。

Do note, that this will only work if the script is loaded with the page load.请注意,这仅在脚本与页面加载一起加载时才有效。 If you want to load it dynamically, this solution will not help you.如果您想动态加载它,此解决方案将无济于事。

PHP PHP

HTML HTML

<head>
    <script type="text/javascript"> <?php echo $decodedstring ?> </script>
</head>

In Summary: Decode with serverside and put it in your HTML using the server language.总结:使用服务器端解码并使用服务器语言将其放入您的 HTML 中。

Here is a safe and reusable function for adding script to head section if its not already exist there.这是一个安全且可重用的函数,用于将脚本添加到 head 部分(如果它不存在)。

see working example here: Example在此处查看工作示例: 示例

<!DOCTYPE html>
<html>
  <head>
    <base href="/"/>
    <style>
    </style>
  </head>
  <body>
    <input type="button" id="" style='width:250px;height:50px;font-size:1.5em;' value="Add Script" onClick="addScript('myscript')"/>
    <script>
      function addScript(filename)
      {
        // house-keeping: if script is allready exist do nothing
        if(document.getElementsByTagName('head')[0].innerHTML.toString().includes(filename + ".js"))
        {
          alert("script is allready exist in head tag!")
        }
        else
        {
          // add the script
          loadScript('/',filename + ".js");
        }
      }
      function loadScript(baseurl,filename)
      {
        var node = document.createElement('script');
        node.src = baseurl + filename;
        document.getElementsByTagName('head')[0].appendChild(node);
        alert("script added");
      }
    </script>
  </body>
</html>
<script type="text/JavaScript">
     var script = document.createElement('SCRIPT');
    script.src = 'YOURJAVASCRIPTURL';
    document.getElementsByTagName('HEAD')[0].appendChild(script);
 </script>

If you want to add a script tag with some script inside, use如果你想添加一个脚本标签,里面有一些脚本,请使用

var script= document.createElement('script');
script.text = "alert('Hi!');";
document.head.appendChild(script);

You can directly use a " Data URL ".您可以直接使用“ 数据 URL ”。 Using the data in your example:使用示例中的数据:

var newScript = document.createElement("script");
newScript.type = "text/javascript";
document.head.appendChild(newScript);
newScript.src = "data:text/plain;base64,YWxlcnQoImhpIik7DQo="

This way, you can skip loading base64.js and directly evaluate the base64 encoded script.这样,您可以跳过加载 base64.js 并直接评估 base64 编码的脚本。

I want to add DOM element to head section of HTML.我想将DOM元素添加到HTML的头部。 jQuery does not allow adding DOM element script to the head section and they execute instead, Reference . jQuery不允许将DOM元素脚本添加到头部,而是执行Reference

I want to add script tags and write a script within <head> section.我想添加script标签并在<head>部分中编写脚本。

var script = '<script type="text/javascript"> //function </script>'
$('head').append(script);

Something like this with functions.这样的功能。 I tried jQuery and javascript\\, but it does not work.我尝试使用jQuery和javascript \\,但无法正常工作。

Please tell me how to add and write script to head by jQuery or javascript.请告诉我如何通过jQuery或javascript添加和编写script

I tired the javascript to add DOM element, but it does not work with .innerHTML() to write to head.我很讨厌用javascript添加DOM元素,但是它不能与.innerHTML()一起写入。 I am using jQuery 2.0.3 and jQuery UI 1.10.3.我正在使用jQuery 2.0.3和jQuery UI 1.10.3。

I want to add base64 encoded script to head section.我想将base64编码的脚本添加到头部。 I use base64 decoder js like this to decode the javascript and then put on the head section.我使用像这样的base64解码器js来解码javascript,然后放在头部。

//Edited //编辑
It will be这将是

$.getScript('base64.js');
var encoded = "YWxlcnQoImhpIik7DQo="; //More text
var decoded = decodeString(encoded);
var script = '<script type="text/javascript">' +decoded + '</script>';
$('head').append(script);

To fit an encoded script and the addition in one javascript file.将编码的脚本和添加的内容放到一个javascript文件中。 I want to use base64.js or some other decoder javascript files for browsers does not accept atob() .我想为浏览器使用base64.js或其他一些解码器javascript文件不接受atob()

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

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