我想在网页中动态地包括一个脚本标签,但我无法控制它的src,所以src="source.js"可能看起来像这样。

document.write('<script type="text/javascript">')
document.write('alert("hello world")')
document.write('</script>')
document.write('<p>goodbye world</p>')

一般来说

<script type="text/javascript" src="source.js"></script>

在头部工作很好,但有没有其他方法,我可以动态添加source.js使用innerHTML之类的东西?

我已经试过了


当前回答

window.addEventListener("load", init); const loadScript = async (url) => { const response = await fetch(url); const script = await response.text(); eval(script); } function init() { const wistiaVideo = document.querySelector(".wistia_embed"); if ("IntersectionObserver" in window && "IntersectionObserverEntry" in window && "intersectionRatio" in window.IntersectionObserverEntry.prototype) { let lazyVideoObserver = new IntersectionObserver(function (entries, observer) { entries.forEach(function (entry) { if (entry.isIntersecting) { setTimeout(() => loadScript("//fast.wistia.com/assets/external/E-v1.js"), 1000); lazyVideoObserver.unobserve(entry.target); console.log("E-v1.js script loaded from fast.wistia.com"); } }); }); lazyVideoObserver.observe(wistiaVideo); } } <div style="height: 150vh; background-color: #f7f7f7;"></div> <h1>Wistia Video!</h1> <div class="wistia_embed wistia_async_29b0fbf547" style="width:640px;height:360px;">&nbsp;</div> <h1>Video Ended!</h1>

其他回答

window.addEventListener("load", init); const loadScript = async (url) => { const response = await fetch(url); const script = await response.text(); eval(script); } function init() { const wistiaVideo = document.querySelector(".wistia_embed"); if ("IntersectionObserver" in window && "IntersectionObserverEntry" in window && "intersectionRatio" in window.IntersectionObserverEntry.prototype) { let lazyVideoObserver = new IntersectionObserver(function (entries, observer) { entries.forEach(function (entry) { if (entry.isIntersecting) { setTimeout(() => loadScript("//fast.wistia.com/assets/external/E-v1.js"), 1000); lazyVideoObserver.unobserve(entry.target); console.log("E-v1.js script loaded from fast.wistia.com"); } }); }); lazyVideoObserver.observe(wistiaVideo); } } <div style="height: 150vh; background-color: #f7f7f7;"></div> <h1>Wistia Video!</h1> <div class="wistia_embed wistia_async_29b0fbf547" style="width:640px;height:360px;">&nbsp;</div> <h1>Video Ended!</h1>

我写了一个漂亮的小脚本来加载多个脚本:

function scriptLoader(scripts, callback) {

    var count = scripts.length;

    function urlCallback(url) {
        return function () {
            console.log(url + ' was loaded (' + --count + ' more scripts remaining).');
            if (count < 1) {
                callback();
            }
        };
    }

    function loadScript(url) {
        var s = document.createElement('script');
        s.setAttribute('src', url);
        s.onload = urlCallback(url);
        document.head.appendChild(s);
    }

    for (var script of scripts) {
        loadScript(script);
    }
};

用法:

scriptLoader(['a.js','b.js'], function() {
    // use code from a.js or b.js
});

有多种方法可以包含动态javascript, 我在很多项目中都使用这个。

var script = document.createElement("script")
script.type = "text/javascript";
//Chrome,Firefox, Opera, Safari 3+
script.onload = function(){
console.log("Script is loaded");
};
script.src = "file1.js";
document.getElementsByTagName("head")[0].appendChild(script);

你可以调用create一个通用函数,它可以帮助你根据需要加载尽可能多的javascript文件。这里有一个完整的教程。

正确地插入动态Javascript

以正确的顺序加载相互依赖的脚本。

基于Satyam Pathak的响应,但修复了onload。 它是在脚本实际加载之前触发的。

const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js'] let count = 0 const recursivelyAddScript = (script, cb) => { const el = document.createElement('script') el.src = script if(count < scripts.length) { count ++ el.onload = () => recursivelyAddScript(scripts[count]) document.body.appendChild(el) } else { console.log('All script loaded') return } } recursivelyAddScript(scripts[count])

我尝试递归地追加每个脚本

注意:如果你的脚本是一个接一个的,那么位置需要同步。

Major Dependency应该在数组的最后,以便初始脚本可以使用它

const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js'] let count = 0 const recursivelyAddScript = (script, cb) => { const el = document.createElement('script') el.src = script if(count < scripts.length) { count ++ el.onload = recursivelyAddScript(scripts[count]) document.body.appendChild(el) } else { console.log('All script loaded') return } } recursivelyAddScript(scripts[count])