I am trying to load some JavaScript files via a custom loader. Previously I was using document.write() to write all of my files out, but I want to make use of jQuery. I'm definitely no expert in jQuery, only using some of the more basic features and functionality, so I took to the web. Well, i found the following piece of code, which DOES work, but I'm having a little trouble understanding it. Here is the code:
(function() {
// Poll for jQuery to come into existence
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
}
else {
window.setTimeout(function() { checkReady(callback); }, 100);
}
};
// Start polling...
checkReady(function($) {
// Use $ here...
});
})();
I understand the fact that the code is checking to see if jQuery is available, and if not, it will keep checking every second. I also understand the fact that if it is available, the code under the "Polling" will execute. What I'm not understanding, and what I'm having a hard time wrapping my brain around, is the whole callback parameter and the checkReady variable.
checkReady is both a variable as well as a function? If it's a variable which is a function in the top section, how can it have a different function associated with it in the code in the lower section? Also, what is the callback parameter actually doing?
In Javascript, functions are first-class, meaning that they can be assigned to variables, passed as arguments and treated as you would any other variable, like a 5 or "foo".
What you're seeing here var checkReady = function(callback) { ... } is the function being assigned to the variable checkReady.
What you're seeing here checkReady(function($) { ... }); is checkReady being called with the anonymous function function($) { ... } as its argument. Inside the function checkReady this is referred to with the callback parameter. An anonymous function just means you have a literal function there without a name, just like having a string literal "foo" you can call alert("foo"); without naming it var str="foo"; alert(str); You can do the same thing with functions. They can be named or put inline as literal things without names.
What you're seeing here window.setTimeout(function() { checkReady(callback); }, 100); is window.setTimeout being called with an anonymous function function() { ... }, set to be executed in 100 milliseconds. In 100 milliseconds, it executes the function, which contains a recursive call back to checkReady with the same callback argument it got in the first place.
So what is callback doing? It's intended to contain everything you want to do after you're sure JQuery is loaded. Basically it's the substance of your program. You're passing your whole program around like it's any other variable, to another function that checks things every so often and calls it when it's ready. This is the beauty of first-class functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With