Open In App

How to tell if a script tag failed to load?

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The problem is to identify whether the passed script loaded successfully or not using JavaScript. There are two methods which are discussed below

Approach 1:

  • Set a variable loaded = false.
  • Pass the URL of the JavaScript file in the <script> tag.
  • Set the onload parameter, if the script loaded set loaded = true.

Example: This example illustrates the approach discussed above. 

html




<script>
    var loaded = false;
</script>
<script src=
        onload="loaded=true;">
</script>
<h1 style="color:green;">
    GeeksforGeeks
</h1>
<p id="GFG_UP">
</p>
<button onclick="gfg_Run()">
    Click here
</button>
<p id="GFG_DOWN">
</p>
<script>
    var el_up = document.getElementById("GFG_UP");
    var el_down = document.getElementById("GFG_DOWN");
 
    el_up.innerHTML = "Click on the button to check "
        + "whether script is loaded or not.";
 
    function gfg_Run() {
        if (loaded) {
            el_down.innerHTML = "Loaded Successfully!";
        }
        else {
            el_down.innerHTML = "Not loaded!";
        }
    }       
</script>


Output:

<img src="https://media.geeksforgeeks.org/wp-content/uploads/20230119103231/gfg.gif" alt="How to tell if a tag failed to load?” srcset=”https://media.geeksforgeeks.org/wp-content/uploads/20230119103231/gfg.gif 495w, ” sizes=”100vw” width=”495″>
How to tell if a <script> tag failed to load?

Approach 2:

  • Set a variable loaded = false.
  • Pass the URL of the JavaScript file in a <script> tag.
  • Set the onload parameter, Trigger alert if script loaded.
  • If not then check for loaded variable, if it is equal to false, then script not loaded.

Example: This example follows the approach discussed above. 

html




<script>
    var loaded = false;
</script>
 
<script src="" onload="alert('Script loaded!'); loaded=true;">
</script>
 
<h1 style="color:green;">
    GeeksforGeeks
</h1>
 
<p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
</p>
 
<script>
    var el_up = document.getElementById("GFG_UP");
    el_up.innerHTML = "Click on the refresh button "
        + "to check whether script is loaded or not.";
 
    if (!loaded) {
        alert("Script not loaded!");
    }
</script>


Output:

<img src="https://media.geeksforgeeks.org/wp-content/uploads/20230119103424/gfg.gif" alt="How to tell if a tag failed to load?” srcset=”https://media.geeksforgeeks.org/wp-content/uploads/20230119103424/gfg.gif 575w, ” sizes=”100vw” width=”575″>
How to tell if a <script> tag failed to load?


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads