Sunday, February 22, 2026
HomeLanguagesJavascriptHow to tell if a script tag failed to load?

How to tell if a script tag failed to load?

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;">
    neveropen
</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;">
    neveropen
</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?
RELATED ARTICLES

Most Popular

Dominic
32506 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6882 POSTS0 COMMENTS
Nicole Veronica
12005 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12099 POSTS0 COMMENTS
Shaida Kate Naidoo
7011 POSTS0 COMMENTS
Ted Musemwa
7255 POSTS0 COMMENTS
Thapelo Manthata
6967 POSTS0 COMMENTS
Umr Jansen
6956 POSTS0 COMMENTS