Reputation: 5263
I switched to using Require.JS in an app and immediately faced this problem:
I used to use inline JS to initiate certain calls once certain part of DOM is loaded. Now apparently jQuery loads only after those calls are executed, thus resulting in errors because jQuery ($) is undefined.
What's the best way to enqueue callbacks for jQuery before it's loaded? I need them to fire either immediately if jQuery is already loaded, or immediately once it's loaded.
Upvotes: 0
Views: 140
Reputation: 20704
This is what I do
var _DomReadyCallback = _DomReadyCallback || [];
_DomReadyCallback.push(function() {
alert('Jquery Loaded');
});
After jQuery is loaded loop through the array and invoke all the callbacks
// This code should come after jQuery is loaded (add it on the jQuery onload callback or append it at the end of the jQuery file)
$(function(){
for (var cb in _DomReadyCallback) {
cb.call();
}
});
OR
requirejs(['jquery'], function ($) {
for (var cb in _DomReadyCallback) {
cb.call();
}
});
Upvotes: 2
Reputation: 708036
You have selected two mutually incompatible scripting techniques:
You simply can't do both of those together. If you really need to load jQuery in a deferred fashion, then you will have to also defer the use of jQuery until jQuery is loaded. Requires.js has an optional callback that will let you know when jQuery is loaded. At that point, you can then run your other initialization jQuery code.
If you wanted to keep as much of both of these as possible, you could have each piece of inline JS register a callback into an array of callbacks and then create a function that will execute all those callbacks when jQuery gets loaded. I'd be a bit surprised if what you're trying to accomplish is worth this much trouble.
I'd suggest that if you want inline javascript to execute as soon as possible, then either make it independent of jQuery (so it can run any time) or stop deferring the load of jQuery so it can be used as your DOM loads.
Upvotes: 1