2

First, this is not a duplicate of this question... And you'll see why in a second.

I have a file that I want to reference in my HTML

    <script src="dist/js/script.js"></script>

But I want to check if it was loaded or not and when it loads I want to do something with it...

I have tried using the load event(addEventListener) but for some reason (I think because I have async features in the external file) it doesn't work.

I'm using an inline script tag after the external file and this (inline script) block of code gets executed before the script tag above it (The external file), and I want the external file to load first before my inline script

How can I make it so that the inline <script> runs after my external file has been 100% loaded?

4
  • Did you try window.onload ?
    – greentec
    Commented Jul 25, 2020 at 4:29
  • 1
    My God! This magically worked! Please, make it an answer and I'm going to approve it. Thanks a lot Commented Jul 25, 2020 at 4:31
  • Why can't you include inline script in side the JavaScript file after executing all the functions in the JavaScript file .so it will work like you were thinking. Commented Jul 25, 2020 at 4:33
  • Because the external file is Front-end written and the inline script is written from the backend Commented Jul 25, 2020 at 4:34

2 Answers 2

3

Try window.onload. This event fires after all scripts are loaded.

function init() {
    // your code
}

window.onload = init;
1
  • I didn't know window.onload knows about async stuff as well. I thought it was just for the DOM elements being there and that's it... But this worked like a charm Commented Jul 25, 2020 at 4:33
1

Attach an function to the load event: <script src="dist/js/script.js" onload ="SomeFunction()"></script>

2

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.