How to Tell If a <Script> Tag Failed to Load

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



Leave a reply



Submit