jQuery - How to check for available javascript on a page?
On a html page that uses $.getScript to dynamically load .js files.
Later at some point if I wish to check whether a particular .js file is loaded. How to do this?
Can I check using filename.js? or do I have to check for an object/function/variable in tha开发者_运维技巧t file?
Thanks for the answers folks. You guys suggested callback function, global variable etc. But the thing is, I work in corporate environment where one corporate .js loads other .js(the one I'm trying to detect). Not only I can't modify corporate .js, I can't control when it'll change. I was hoping may be there was a way to know which .js file is loaded on page.
The quickest way to test for this is to test for the existence of a function or variable that was declared in the JavaScript file you loaded.
if(typeof foo == "undefined") {
//JS has loaded
} else {
//JS has not loaded
}
A global object?
var loadedFiles = {};
$.getScript('filename.js');
loadedFiles['filename.js'] = true;
// later...
if (loadedFiles['filename.js']) {
// Do stuff...
}
If there are objects unique to that JS file then yes, you could also just check for the existence of an object/function/variable.
EDIT - karim79's method using an onSuccess method would be more reliable, although you could still keep your results namespaced inside the global-object.
Fire some event in the script you are loading to notify parent script about that fact that script is loaded. Store information into some array in some global class. Write simple function which will find filename in this array - isLoaded(filename).
I would recommend firing a custom event in the callback which will notify you of 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');
});
I guess one way would be to set some global booleans (or whatever):
var fooLoaded = false;
var barLoaded = false;
and set them in $.getScript
's callback:
$(document).ready(function() {
$.getScript("/some/script.js", function(){
fooLoaded = true;
});
if(fooLoaded) {
...
}
});
That said, I think in general it would be better practice to do whatever needs to be done upon the loading of the script within the success callback.
You can check for the type of the element to see whether it is a function as below.
function callClient(){
if (typeof myTestFunction == 'function') {
myTestFunction();
} else {
alert("myTestFunction function not available");
}
}
Above is extracted from "Verify calling Javascript function available to avoid runtime errors"
精彩评论