Skip to content

Instantly share code, notes, and snippets.

@ivankolesnik
Created July 19, 2016 13:19
Show Gist options
  • Save ivankolesnik/72a4b421cb3dde655cfa710cc2102a87 to your computer and use it in GitHub Desktop.
Save ivankolesnik/72a4b421cb3dde655cfa710cc2102a87 to your computer and use it in GitHub Desktop.
Watch for async loaded remote scripts
/*
* This is a function that watches global variable
* Used to track asynchronously loaded remote scripts that do not have 'onload' callbacks
* When variable is created, callback {name}AsyncInit will be called
* And this 'watcher' will be replaced by real object
*
* Usage:
* window.somelibAsyncInit = function(somelib){...}
* window.__loadAsync('somelib')
*
* Based on ideas of 'watch' polyfill https://gist.github.com/eligrey/384583
*/
window.__loadAsync = function(name) {
if (typeof name !== 'string') { throw 'Invalid object name!' }
// Defining names for temp variable and callback function
var oldVal = window[name],
newVal = oldVal,
cbName = name + 'AsyncInit',
timeout;
// Creating 'watcher' object that will catch the real object
Object.defineProperty(window, name, {
configurable: true,
enumerable: true,
set: function(value) {
// Assigning new value
newVal = value;
// Already fired callback
if (typeof timeout === 'number') { return }
// Property is undefined or empty
// Some libraries assign empty object at first
if (!Object.keys(newVal).length) { return }
// Cleanup and fire callbacks next tick
// Some libraries are not initialized fully until next tick
timeout = setTimeout(function() {
// Making us writable so we can be replaced
Object.defineProperty(window, name, {writable: true});
// Cleanup
delete window[name];
// Replacing 'watcher' with real object
Object.defineProperty(window, name, {
configurable: true,
enumerable: true,
writable: true,
value: newVal
});
newVal = undefined;
// Calling callback if exists
if (typeof window[cbName] === 'function') {
// Pass in new value
window[cbName](window[name]);
}
}, 0);
},
get: function() {
return newVal;
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment