Can't insert js programmatically if it uses [removed]

后端 未结 4 2058
别跟我提以往
别跟我提以往 2021-01-22 23:12

I am trying to insert js files programmatically, using jquery and something like this:

var script = document.createElement( \'script\' );
script.type = \'text/ja         


        
相关标签:
4条回答
  • 2021-01-22 23:40

    There isn't anything wrong with your approach to inserting JavaScript. document.write just sucks a little bit. It is only for synchronous tasks, so putting a document.write in a separate script file is asking for trouble. People do it anyway. The solution I've seen most often for this is to override document.write.

    0 讨论(0)
  • 2021-01-22 23:44

    Document.write is ONLY for synchronous tasks when the html is loaded (for the very first time), never for asynchronous tasks like the one you are trying to do.

    0 讨论(0)
  • 2021-01-22 23:46

    use innerHTML instead of using document,write.

    and use following code to register script,

    (function() {
        var jq = document.createElement('script');
        jq.type = 'text/javascript';
        jq.async = true;
        jq.src = 'http://someurl/test.js';
        var s = document.body.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(jq, s);
    })();
    
    0 讨论(0)
  • 2021-01-22 23:54

    What you want to do is dynamically insert a <script> DOM element into the HEAD element. I had this script sitting around. As an example, it's a race condition, but you get the idea. Call load_js with the URL. This is done for many modern APIs, and it's your best friend for cross-domain JavaScript.

    <html>
        <head>
            <script>
                var load_js = function(data, callback)
                {
                        var head = document.getElementsByTagName("head")[0];
    
                        var script = document.createElement("script");
                        script.type = "text/javascript";
                        script.src = data;
                        head.appendChild(script);
    
                        if(callback != undefined)
                                callback();
                }
    
                load_js("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js");
    
                setTimeout(function() {
                    $('body').html('loaded');
                }, 1000);
            </script>
        </head>
    
        <body></body>
    </html>
    
    0 讨论(0)
提交回复
热议问题