JQuery - How to check for available javascript on a page?
In a html page that uses $ .getScript to dynamically load .js files.
Later at some point if I want to check if any .js file is loaded. How to do it?
Is it possible to check the use of filename.js? or do I need to check an object / function / variable in this file?
Thanks for answers. You guys suggested a callback function, global variable, etc. But the thing is, I am working in an enterprise environment where one enterprise .js is loading another .js (the one I am trying to detect). Not only can I not change the corporate .js, I have no control over when it will change. I was hoping there was a way to find out which .js file is loaded on the page.
source to share
I guess one way would be to set some global booleans (or whatever):
var fooLoaded = false;
var barLoaded = false;
and set them in $.getScript
the callback:
$(document).ready(function() {
$.getScript("/some/script.js", function(){
fooLoaded = true;
});
if(fooLoaded) {
...
}
});
However, I think in general it would be better to do whatever has to be done when loading the script in the success callback.
source to share
Global object?
var loadedFiles = {};
$.getScript('filename.js');
loadedFiles['filename.js'] = true;
// later...
if (loadedFiles['filename.js']) {
// Do stuff...
}
If there are objects unique to this JS file, then yes, you can also just check for the existence of the object / function / variable.
EDIT - karim79's method using the onSuccess method would be more reliable, although you could store your results in a namespace inside a global object.
source to share
I would recommend firing a custom event in a callback that will notify you when your script has loaded. You will need to use the .bind () method to bind the custom event to something, and .trigger () to fire that event from the callback. For example, something like this:
$('body').bind('foo', function() {
// do something
});
$.getScript(url, function() {
$('body').trigger('foo');
});
source to share
You can check the type of the element to see if it is a function as shown below.
function callClient(){
if (typeof myTestFunction == 'function') {
myTestFunction();
} else {
alert("myTestFunction function not available");
}
}
Above is extracted from Check Javascript Function Accessibility to Prevent Runtime Errors
source to share