Skip to content

Instantly share code, notes, and snippets.

@dansajin
Last active May 31, 2017 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansajin/363ea036975885b94b62c32a14c45500 to your computer and use it in GitHub Desktop.
Save dansajin/363ea036975885b94b62c32a14c45500 to your computer and use it in GitHub Desktop.
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