我想在网页中动态地包括一个脚本标签,但我无法控制它的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之类的东西?

我已经试过了


当前回答

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

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

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])

其他回答

您可以尝试以下代码片段。

function addScript(attribute, text, callback) {
    var s = document.createElement('script');
    for (var attr in attribute) {
        s.setAttribute(attr, attribute[attr] ? attribute[attr] : null)
    }
    s.innerHTML = text;
    s.onload = callback;
    document.body.appendChild(s);
}

addScript({
    src: 'https://www.google.com',
    type: 'text/javascript',
    async: null
}, '<div>innerHTML</div>', function(){});

以下是一个简化的代码片段,与谷歌Analytics和Facebook Pixel使用的代码相同:

!function(e,s,t){(t=e.createElement(s)).async=!0,t.src="https://example.com/foo.js",(e=e.getElementsByTagName(s)[0]).parentNode.insertBefore(t,e)}(document,"script");

将https://example.com/foo.js替换为脚本路径。

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>

当脚本异步加载时,它们不能调用document.write。调用将被忽略,并将警告写入控制台。

你可以使用下面的代码来动态加载脚本:

var scriptElm = document.createElement('script');
scriptElm.src = 'source.js';
document.body.appendChild(scriptElm);

只有当您的源文件属于一个单独的文件时,这种方法才有效。

但如果你有源代码作为内联函数,你想要动态加载,并想要添加其他属性到脚本标签,例如类,类型等,那么下面的代码片段将帮助你:

var scriptElm = document.createElement('script');
scriptElm.setAttribute('class', 'class-name');
var inlineCode = document.createTextNode('alert("hello world")');
scriptElm.appendChild(inlineCode); 
document.body.appendChild(scriptElm);

要做到这一点,唯一的方法是替换文档。使用您自己的函数编写,该函数将在页面底部附加元素。jQuery非常简单:

document.write = function(htmlToWrite) {
  $(htmlToWrite).appendTo('body');
}

如果你有html来文档。像问题样例那样写入块,你需要缓冲htmlToWrite段。也许是这样的:

document.write = (function() {
  var buffer = "";
  var timer;
  return function(htmlPieceToWrite) {
    buffer += htmlPieceToWrite;
    clearTimeout(timer);
    timer = setTimeout(function() {
      $(buffer).appendTo('body');
      buffer = "";
    }, 0)
  }
})()