How to dynamically load and use/call a JavaScript file?

前端 未结 4 1151
萌比男神i
萌比男神i 2020-11-30 13:29

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

File test.js

test = function () {
    var pub = {}
    pub.def         


        
4条回答
  •  北海茫月
    2020-11-30 13:37

    Dinamically loading JS files is asynchronous, so to ensure your script is loaded before calling some function inside, use the onload event in script:

    function loadjs(file) {
                var script = document.createElement("script");
                script.type = "application/javascript";
                script.onload=function(){
                    //at this tine the script is loaded
                    console.log("Script loaded!");
                    console.log(test);
                }
                script.src = file;
                document.body.appendChild(script);
            }
    

提交回复
热议问题