简体   繁体   中英

Trying to run a function from a dynamically loaded javascript script

Hi I need some help here I'm trying to figure out why DOM can't find the functions loaded dynamically from other javascripts files. Some points about what is going on where would be great.

CHROME ERROR: Uncaught ReferenceError: start_canvas is not defined

HTML

<html>
<head>
</head>
<body>
<script src="assets/scripts/main.js" type="text/javascript"></script>
<script type="text/javascript">
    //previous erroneous code load_script("assets/scripts/script.js", ()=>{});
    load_script("assets/scripts/start_canvas.js", ()=>{});
    window.onload = () => start_canvas();
</script>

</body>
</html>

JS - main.js

function load_script(url, callback) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    if (callback != null) {
        script.onload = function () {
            callback();
        };
    }
    document.getElementsByTagName("head")[0].appendChild(script);
}

JS - start_canvas.js

function start_canvas() {
    alert("bar");
}

thanks !

In your code call the callback in the right place

 load_script("assets/scripts/script.js", () => start_canvas());

change your script file name to start_canvas.js . it is assets/scripts/ script.js in your code

 load_script("assets/scripts/start_canvas.js", ()=>{});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM