I'm currently experimenting with async loading of JavaScript and came up with the following trick to detect when jQuery loads:
var jQueryPromise = new Promise(function(resolve) {
Object.defineProperty(window, '$', {
get: function() {
return this.jQuery;
},
set: function(value) {
if (typeof value === 'function') {
resolve(value);
}
}
});
if (typeof jQuery === 'function') {
$ = jQuery;
}
});
jQueryPromise.then(function($) {
// use $ normally here
});
The idea is to have a method which works regardless of how and when jQuery was loaded (via a script
tag, async script
tag, script
created via document.createElement
...)
My aim is really just to understand how to best utilise async loading in general - all comments are welcome, especially regarding possible quirks of this (hacky) approach.
In addition, I'm curious whether there are any performance advantages to loading jQuery async and then waiting for the Promise to resolve using this method over just loading it normally before the script (and in which cases would this performance boost happen)?