如何动态加载和使用/调用JavaScript文件? [英] How to dynamically load and use/call a JavaScript file?

查看:46
本文介绍了如何动态加载和使用/调用JavaScript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要动态加载JavaScript文件,然后访问其内容.

I need to dynamically load a JavaScript file and then access its content.

文件test.js

test = function () {
    var pub = {}
    pub.defult_id = 1;
    return pub;
}()


在这种情况下,它可以正常工作:


In this case it works:

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="/test.js"></script>    
</head>
<body>
    <script type="text/javascript">
        console.log(test.defult_id);
    </script>
</body>
</html>


但是我需要动态加载它,这样它就无法工作:


But I need to load it dynamically, and that way it does not work:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <script type="text/javascript">
        function loadjs(file) {
            var script = document.createElement("script");
            script.type = "application/javascript";
            script.src = file;
            document.body.appendChild(script);
        }
        loadjs('test.js');
        console.log(test.defult_id);
    </script>
</body>
</html>


错误:Uncaught ReferenceError: test is not defined(…)


Error: Uncaught ReferenceError: test is not defined(…)

推荐答案

您可以这样做:

function loadjs(file) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = file;
    script.onload = function(){
        alert("Script is ready!"); 
        console.log(test.defult_id);
    };
    document.body.appendChild(script);
 }

有关更多信息,请阅读本文: https: //www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

For more information read this article : https://www.nczonline.net/blog/2009/06/23/loading-javascript-without-blocking/

这篇关于如何动态加载和使用/调用JavaScript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆