动态附加<script>标记

时间:2017-03-08 10:10:41

标签: javascript jquery dom

我需要使用带有回调函数的jQuery或纯JavaScript动态附加&lt; script&gt;&lt; / script&gt; 标记。

&#xA;&#xA; <请注意两个重要事项:

&#xA;&#xA;

1)标记可能包含更多属性,然后应包含在标记中的'src'。例如:

&#xA;&#xA;
 &lt; script src =“https://code.jquery.com/jquery-3.1.1.min.js”integrity =“sha256 -hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8 =“crossorigin =”anonymous“exclude =”true“&gt;&lt; / script&gt;&#xA;  
&#xA;&#xA;

没有只有网址

&#xA;&#xA;

2)脚本加载后应执行回调功能。

&# XA;&#XA;
&#XA;

这是重复因为我不知道&#xA;脚本包含。

&#xA;
&#xA;

3 个答案:

答案 0 :(得分:1)

我们可以使用追加http://api.jquery.com/append

function addScript(source, callback) {
    var tag = document.createElement("script");
    tag.type = "text/javascript";
    tag.src = source;
    tag.onload = callback;
    $("body").append(tag);
};

答案 1 :(得分:1)

关于元素的创建,你可以拥有这样的函数。然后使用您需要的必要属性调用它。将其附加到DOM,然后按照有关延迟回调的注释,直到脚本加载完毕。

function createElement(element, attributes, text) {
    // function to create an element with class and text if wanted.
    // attributes is an object of key value items. Key is the attribute, value is the value.
    var el = document.createElement(element);
    $.each(attributes, function(key, value) {
        el.setAttribute(key, value);
    });
    if (text) {
        var t = document.createTextNode(text);
        el.appendChild(t);
    }
    return el;
}

可以这样使用:
createElement("script", { "src": "your_src", "tag": "your_tag });

答案 2 :(得分:-2)

看到给定的答案和评论我来到这个解决方案:

  1. 您将脚本标记作为纯文本。
  2. 将它们转换为可迭代的对象,您可以使用$.parseXML()
    对于回调使用node.onload,如下所示:

    var scriptTags = '<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous" exclude="true"></script>';
    
    // keep in mind this even works with multiple script tags inside that string.
    $('script', $.parseXML(scriptTags)).each(function(index, script) {
        var node = document.createElement('script');
    
        $(script.attributes).each(function(index, attribute) {
            node.setAttribute(attribute.name, attribute.value);
        });
    
        node.onload = function() {
            console.log('my body is ready!')
        };
        // you might need other stuff here aswell for IE compatibility etc.
        // thats easily found using google.
        // at this point you have a new script element
        // that you can mess around with.
    
        document.head.appendChild(node);
    });
    
  3. 基本上你甚至可以这样做:$(document.head).append($(scriptTags))但是如果你想要onload事件的回调那么除了我所做的事情之外,你可以做的事情并不多。 在解析像这样的脚本标签时, jquery似乎搞乱了onload事件。
    上面的代码是我在最后几分钟内摆弄的解决方法。

  4. 你应该考虑一个坚固的AMD加载器或类似的 像这样解决这个任务可能会在未经测试的浏览器中引起问题。
  5. 如果你真的打算使用它,只需将我的代码包装成一个接受scriptTags作为参数的函数
    附加您可以创建一个通用的onload函数,只要加载了所有提供的脚本,就会触发回调。
    你基本上可以宣传这一点 从您在评论中所说的内容开始,我假设您将能够自己解决这个问题。
相关问题