小编Jos*_*lie的帖子

如何将 Javascript 文件动态加载到 HTML 中

我对将 JS 文件动态加载到 DOM 中需要什么感到有些困惑。

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

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

我以前认为我必须重新创建,然后将其 append() 到标签。我感觉好像我错过了关键的一步,我只是不知道那一步是什么。

示例.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>
Run Code Online (Sandbox Code Playgroud)

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 …
Run Code Online (Sandbox Code Playgroud)

html javascript

6
推荐指数
1
解决办法
190
查看次数

标签 统计

html ×1

javascript ×1