ghchoi
ghchoi

Reputation: 5156

How to ensure <script> tag successfully load Javascript?

I'm studying to make Web application.

It seems like the script tag

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

fails sometimes.

I've tried to find how to solve it but I cannot find the exact solution yet.

How can I ensure script tag successfully load Javascript?

Thank you for your help in advance.

Upvotes: 0

Views: 2670

Answers (3)

castletheperson
castletheperson

Reputation: 33496

Add a handler for the onerror and/or onload events.

<script>
    function errorHandler(script) {
        script.src = "backupLib.js";
    }
</script>
<script src="someLib.js" onerror="errorHandler(this)"></script>

Upvotes: 4

Sabyasachi Biswal
Sabyasachi Biswal

Reputation: 7

  1. Script tag doesn't have an error event handler.
  2. But we can use onload event handler instead like this :

    <script>
        function fileLoaded(name) {
           console.log('JS File loaded # '+ name  );
           alert('JS File loaded # '+ name  );
        }
    
        function fileLoadingError(name) {
           console.log('File error # '+ name  );
        }
    </script>
    <script src=".../jsFile.js" onload="fileLoaded('1')" onerror="fileLoadingError('1')"></script>
    
  3. Make sure to keep the function first.

  4. Even if there's error, the onload method will be called.

Upvotes: -2

Sankar
Sankar

Reputation: 7107

Browser developer tools will helps you...

Load the website in the browser and open the developer tools then network tab, refresh the page.

There you can see the status of resources, what are all loaded in the page(images,js,css..), If the status code was 200 then it is OK.

enter image description here

Upvotes: 0

Related Questions