Last active
May 31, 2017 08:11
-
-
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
This file contains 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
<!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> |
This file contains 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
'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