How to add DOM element script to head section?

前端 未结 11 977
野趣味
野趣味 2020-11-28 10:54

I want to add DOM element to head section of HTML. jQuery does not allow adding DOM element script to the head section and they execute instead, Reference.

I want t

相关标签:
11条回答
  • 2020-11-28 11:00
    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

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

    0 讨论(0)
  • 2020-11-28 11:02

    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);
    
    0 讨论(0)
  • 2020-11-28 11:03
    <script type="text/JavaScript">
         var script = document.createElement('SCRIPT');
        script.src = 'YOURJAVASCRIPTURL';
        document.getElementsByTagName('HEAD')[0].appendChild(script);
     </script>
    
    0 讨论(0)
  • 2020-11-28 11:05

    try this

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'url';    
    
    document.getElementsByTagName('head')[0].appendChild(script);
    
    0 讨论(0)
  • 2020-11-28 11:09

    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.

    That may possibly be done as such:

    var script = document.createTextNode("<script>alert('Hi!');</script>");   
    document.getElementsByTagName('head')[0].appendChild(script);
    
    0 讨论(0)
  • 2020-11-28 11:10

    try out ::

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

    0 讨论(0)
提交回复
热议问题