Skip to content

Instantly share code, notes, and snippets.

@carlosascari
Last active October 23, 2015 06:09
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 carlosascari/b324783f7d25f76630b9 to your computer and use it in GitHub Desktop.
Save carlosascari/b324783f7d25f76630b9 to your computer and use it in GitHub Desktop.
Guarantee a module has loaded before executing.
/**
* Tiny Require
*/
/**
* Before the module has finished downloading/evaluating,
* the callback provided is executed async. Once loaded, all
* callbacks will be executed immediately.
*
* A module is detected when it is available in the window object.
*
* @param n {String} Name of global to wait for, e.g jQuery
* @param c {Function} Callback to execute when module is available.
* @param [i] {Number} Interval to check if module is ready. Default: 100ms
*/
function r(n,c,i){w=window,(w[n])?c():setTimeout(r,i=i|0||100,n,c,i)}
/**
* @example (test.html)
*
* <!-- Reusable -->
* <script type="text/javascript">
* function r(n,c,i){w=window,(w[n])?c():setTimeout(r,i=i|0||100,n,c,i)}
* r('jQuery',function(){
* console.log('[A] hello jQuery %o [ASYNC]', $)
* r('jQuery',function(){
* console.log('[A] hello jQuery %o [SYNC]', $)
* })
* })
* </script>
*
* <!-- Dropp In -->
* <script type="text/javascript">
* +function r(n,c,i){w=window,(w[n])?c():setTimeout(r,i=i|0||100,n,c,i)}('jQuery',function(){
* console.log('hello jQuery %o [DROP_IN]', $)
* })
* </script>
*
* <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment