0

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 !

3
  • Where is 'start_canvas.js' being loaded? None of the code you have shown accomplishes that. Commented Jan 4, 2021 at 18:48
  • @terrymorse you are right changing it Commented Jan 4, 2021 at 19:11
  • slaps my own face THANK YOU BOWS Commented Jan 4, 2021 at 19:12

2 Answers 2

2

In your code call the callback in the right place

 load_script("assets/scripts/script.js", () => start_canvas());
Sign up to request clarification or add additional context in comments.

Comments

1

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

3 Comments

yes it is sorry I didn't simplified that but I'm working in a larger project the path is correct
your codes work well if references/paths are well
thank you yeah I did edit the question it was a path error !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.