How to ensure script tag successfully load Javascript?
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>
how can I check if an external javascript has failed to load?
At the top of your <head>
<script>
function scriptfail(element) {
alert('failed to load ' + element.src);
}
</script>
In your script element
<script src="url1" onerror='scriptfail(this);'></script>
Verify External Script Is Loaded
If the script creates any variables or functions in the global space you can check for their existance:
External JS (in global scope) --
var myCustomFlag = true;
And to check if this has run:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
Update
You can check for the existence of the <script>
tag in question by selecting all of the <script>
elements and checking their src
attributes:
//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
return ($(this).attr('src') == '<external JS>');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
$.getScript('<external JS>');
}
Or you can just bake this .filter()
functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
Related Topics
Mediastream Capture Canvas and Audio Simultaneously
R Networkd3 Package: Node Coloring in Simplenetwork()
How to Show Modal Window in Controller's Action
Wkwebkit JavaScript Execution When Not Attached to a View Hierarchy
How to Write Asynchronous Functions for Node.Js
Accessing ASP.NET Controls Using Jquery (All Options)
What Is an Exclamation Point in JavaScript
Shiny: Start the App with Hidden Tabs, with No Delay
How to Get All Arguments of a Function as Single Object Inside That Function
Draggable Line Chart in R/Shiny
Jquery Clone() Not Cloning Event Bindings, Even with On()
Remove Duplicates Form an Array
How to Include Js.Erb File in View Folder
In R, How to Display Value on the Links/Paths of Sankey Graph
Deprecation Warning in Moment.Js - Not in a Recognized Iso Format
How to Add/Remove a Class in JavaScript