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

其他回答

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

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
});

有onload函数,可以在脚本成功加载时调用:

function addScript( src, callback ) {
  var s = document.createElement( 'script' );
  s.setAttribute( 'src', src );
  s.onload=callback;
  document.body.appendChild( s );
}

你可以像这样使用document.createElement()函数:

function addScript( src ) {
  var s = document.createElement( 'script' );
  s.setAttribute( 'src', src );
  document.body.appendChild( s );
}

以下是一个简化的代码片段,与谷歌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替换为脚本路径。

这是我的工作。

你可以检查一下。

var script_tag = document.createElement('script'); script_tag.setAttribute(“src”、“https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js”); document.head.appendChild (script_tag); 窗口。Onload = function() { if (window.jQuery) { //加载jQuery 警报(“在头部添加脚本标签!”); }其他{ //不加载jQuery 警告(“没有在头部添加脚本标签”); } }