Skip to content

Instantly share code, notes, and snippets.



Last active May 31, 2017
What would you like to do?
Async queue pattern - helpful when you need server side parsing in your javascript
<!doctype html>
<!-- some html -->
// define a queue function with cached callbacks
window.queue = window.queue || function(callback){
(queue.callbacks = queue.callbacks || []).push(callback)
<!-- some html -->
// queue until script loads or execute immediately if script is loaded
// some js with server side parsing
var name = '<?= htmlspecialchars($user->name) ?>';
<!-- more html -->
<!-- allow modern browsers to preload the script but do not block old browsers -->
<script defer src="Queue.js"></script>
'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.')
// 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