Skip to content

Instantly share code, notes, and snippets.

@dansajin

dansajin/Queue.js

Last active May 31, 2017
Embed
What would you like to do?
Async queue pattern - helpful when you need server side parsing in your javascript
<!doctype html>
<html>
<head>
<!-- some html -->
<script>
// define a queue function with cached callbacks
window.queue = window.queue || function(callback){
(queue.callbacks = queue.callbacks || []).push(callback)
};
</script>
</head>
<body>
<!-- some html -->
<script>
// queue until script loads or execute immediately if script is loaded
queue(function(){
// some js with server side parsing
var name = '<?= htmlspecialchars($user->name) ?>';
});
</script>
<!-- more html -->
<!-- allow modern browsers to preload the script but do not block old browsers -->
<script defer src="Queue.js"></script>
</body>
</html>
'use strict';
function Queue(){
this.push = function(){
for (var i = 0, len = arguments.length; i < len; i++){
if (typeof arguments[i] !== 'function'){
throw new TypeError('Argument must be a function.')
}
arguments[i]()
}
}
};
// get existing queue callbacks
var oldQueue = window.queue.callbacks;
// create a new queue object which replaces original [].push with new Queue().push
window.queue.callbacks = new Queue();
// execute all of the queued up callbacks
window.queue.callbacks.push.apply(window.queue.callbacks, oldQueue);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment