Cranky Unicorn
Cranky Unicorn

Reputation: 47

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 !

Upvotes: 0

Views: 96

Answers (2)

mehmetx
mehmetx

Reputation: 860

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", ()=>{});

Upvotes: 1

uke
uke

Reputation: 891

In your code call the callback in the right place

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

Upvotes: 2

Related Questions