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("https://stackoverflow.com/questions/9521298/<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') == "https://stackoverflow.com/questions/9521298/<external JS>");
}).length;

//if there are no scripts that match, the load it
if (len === 0) {
    $.getScript("https://stackoverflow.com/questions/9521298/<external JS>");
}

Or you can just bake this .filter() functionality right into the selector:

var len = $('script[src="https://stackoverflow.com/questions/9521298/<external JS>"]').length;

Leave a Comment