How to tell if a script tag failed to load?
Last Updated :
26 Apr, 2023
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:
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:
Share your thoughts in the comments
Please Login to comment...