【问题标题】:How to Dynamically Load Javascript File into HTML如何将 Javascript 文件动态加载到 HTML 中
【发布时间】:2019-12-29 23:59:35
【问题描述】:

我对将 JS 文件动态加载到 DOM 所需的内容有点困惑。

当我包含在我的 HTML 文件中时,example.js 将正常运行。

当我包含它时,它将添加到 DOM 但不运行它。

我之前认为我必须重新创建 ,然后将其 append() 到标签中。感觉好像少了一个关键步骤,就是不知道那一步是什么。

example.html

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <script src="example.js"></script><!-- working -->
    <script src="add-example-dynamically.js"></script><!-- not working -->
</head>
<body>
    <script>
        execute( anyScriptElement ); // not working
    </script>
</body>
</html>
</body>
</html>

add-example-dynamically.js

function toExecutable( tagElement ){
    // Duplicate the provided tag as a new element in order for all tags to run the 'src' attribute after adding it to the DOM
    // Required to run: <script src=""></script>
    var newTag = document.createElement( tagElement.tagName );

    if( tagElement.hasAttributes() ){
        // Check if the tag has attributes
        for( var countAttributes = 0; countAttributes < tagElement.attributes.length; ++countAttributes ){
            var name = tagElement.attributes[ countAttributes ].name;
            var value = tagElement.attributes[ countAttributes ].value;
            newTag.setAttribute( name, value );
        }
    }
    if( tagElement.textContent ){
        // Check if the tag has content within it
        newTag.textContent = tagElement.textContent;
    }
    return newTag;
}
function execute( anyScriptElement ){
    var tag = toExecutable( anyScriptElement );
    document.getElementsByTagName( 'head' )[ 0 ].append( tag );
}
var theScript = document.createElement( 'script' );
theScript.src = 'example.js';
execute( theScript ); // not working

我尝试过(或变体)的事情

error loading javascript files dynamically

我也一直在将.onload.onreadystatechange 添加到各种对象,但没有成功。

我还不太明白的事情

Dynamically load a JavaScript file

How do you import multiple javascript files in HTML index file without the bloat?

Dynamically load a JavaScript file

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://cleverbeagle.com/blog/articles/tutorial-how-to-load-third-party-scripts-dynamically-in-javascript

https://humanwhocodes.com/blog/2009/07/28/the-best-way-to-load-external-javascript/

我认为不能解决我的问题的事情

http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

https://gomakethings.com/a-better-way-to-load-scripts-with-javascript-or-why-document-write-sucks/

想法

我感觉正确的解决方案不涉及 XMLHttpRequest 或 Promises,但我不确定。

我的仓库:Widgets

如果有人能指出我正确的方向,那将帮助我弄清楚我需要研究什么。

仅供参考

Native JS 理想,对 JQuery 不感兴趣。

我只关心对 Chrome、Firefox、Opera、Safari(桌面/移动)的支持

【问题讨论】:

  • 动态脚本标签是如何插入到DOM中的?如果您通过appendChild 执行此操作,则不需要任何其他操作,它应该执行
  • 所以我使用 XMLHttpRequest 从 HTML 文件中获取脚本标签。一旦请求状态 === 200 和 readyState === 4,我在每个标签上使用我的 toExecutable 函数,然后将它们附加到 example.html 中的 标签。
  • 这就是我在示例中没有声明 anyScriptElement 的原因,因为该部分似乎大部分都在工作。我只是想不通为什么它将包含 JS 源的脚本添加到 DOM 但不执行 JS 文件。
  • 一旦你有了想要以responseText 执行的响应文本,只需执行document.body.appendChild(document.createElement('script')).textContent = responseText,我认为应该可行
  • 尝试了以下方法(htmlCollection 是一个包含head 对象作为html 集合的变量): (1) domHead.textContent = theRequest.responseText; // 添加 html 作为引用的“字符串” (2) domHead.textContent = htmlCollection.innerHTML; // 添加 html 作为引用的 "string" (3) domHead.textContent = htmlCollection.innerHTML.replace('"',''); // 添加 html 作为引用的 "string"

标签: javascript html


【解决方案1】:

所以我发现问题出在我解析代码的顺序上。花了很长时间才找到,因为我的代码本质上没有任何问题,但顺序是错误的。

我以正确的顺序调用所有内容,但在我的网络面板中解决问题的顺序不正确。

一旦我确定了将事物加载到 DOM 中的顺序,一切都按预期工作。

修复 #1

因为我的 XMLHttpReqests 应该是异步的,所以我将所有调用放在一个 Javascript 文件中,以便它们同步运行。

在加载引用这些文件的函数调用之前,我需要在标记中加载 Javascript 文件。

我在window.onload = function(){} 中封装的函数调用。

基本上,我的最终解决方案是针对我动态放置在 example.html 中的任何 &lt;script&gt;code&lt;/script&gt;,我将包装在 window.onload = function(){} 中。

&lt;script&gt;window.onload = function(){ code }&lt;/script&gt;

修复 #2

我在一个没有意义的位置使用了 onload 包装器window.onload = function(){}。此外,它可能在调试时嵌套在另一个 window.onload 函数中,这可能没有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-16
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多