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 script loaded set loaded = true.
Example:This example illustrate the approach discussed above.
<!DOCTYPE HTML> < html > < head > < title > How to tell if a script tag failed to load in JavaScript ? </ title > < script > var loaded = false; </ script > < script src = onload = "loaded=true;" > </ script > </ head > < body style = "text-align:center;" > < h1 style = "color:green;" > GeeksgorGeeks </ h1 > < p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;" > </ p > < button onclick = "gfg_Run()" > Click here </ button > < p id = "GFG_DOWN" style = "font-size: 23px; font-weight: bold; color: green; " > </ 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 > </ body > </ html > |
chevron_right
filter_none
Output:
- Before clicking on the button:
- After clicking on the button:
Approach 2:
- Set a variable loaded = false.
- Pass the URL of 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.
<!DOCTYPE HTML> < html > < head > < title > How to tell if a script tag failed to load in JavaScript ? </ title > < script > var loaded = false; </ script > < script src = "" onload = "alert('Script loaded!'); loaded=true;" > </ script > </ head > < body style = "text-align:center;" id = "body" > < 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 > </ body > </ html > |
chevron_right
filter_none
Output:
- Before clicking on the button:
- After clicking on the refresh button: