Created
July 23, 2014 15:31
-
-
Save joshuabaker/9bd92f9ce52aa97f9057 to your computer and use it in GitHub Desktop.
Sample script to load a script asynchronously whilst queuing method calls. Inspired by the Google Analytics tracking code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Placed into HTML | |
(function(window, document, tag, src, property, script, before) | |
{ | |
window['LoaderObject'] = property; | |
window[property] = window[property] || function() | |
{ | |
(window[property].q = window[property].q || []).push(arguments); | |
} | |
script = document.createElement(tag); | |
script.async = 1; | |
script.src = src; | |
document.getElementsByTagName(tag)[0].parentNode.insertBefore(script, before); | |
}(window, document, 'script', '/path/to/loader.js', 'loader')); | |
// Queue instance method | |
loader('someMethod', 'string', 1234); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(window, document) | |
{ | |
var property = window['LoaderObject'], | |
loader = window[property], | |
params; | |
loader.someMethod = function(str, num) | |
{ | |
console.log('someMethod called', str, num); | |
}; | |
for (var i in loader.q || []) | |
{ | |
params = Array.prototype.slice.call(loader.q[i]); | |
loader[params.shift()].apply(loader, params); | |
} | |
}(window, document)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment