« Back to Index

RequireJS Async Load Plugin

View original Gist on GitHub

Tags: #js

gistfile1.js

/*!
 * RequireJS plugin for async dependency load like JSONP and Google Maps
 * @author Miller Medeiros
 * @version 0.0.1 (2011/03/23)
 * Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
 */
define(function(){
	
	function injectScript(src){
		var s, t;
		s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = src;
		t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s,t);
	}
	
	function formatUrl(name, id){
		var paramRegex = /!(.+)/,
			url = name.replace(paramRegex, ''),
			param = (paramRegex.test(name))? name.replace(/.+!/, '') : 'callback'; //default param name is 'callback'
		url += (url.indexOf('?') < 0)? '?' : '&';
		return url + param +'='+ id;
	}
	
	return{
		load : function(name, req, onLoad, config){
			if(config.isBuild){
				onLoad(null); //avoid errors on the optimizer
			}else{
				var id = '__mm_asynch_req__'+ (+new Date());
				window[id] = onLoad; //create a global variable that stores onLoad so callback function can define new module after async load
				injectScript(formatUrl(name, id));
			}
		}
	};
});

gistfile2.js

/*
* Google Maps Example using RequireJS Async plugin
* @author Miller Medeiros
* released under the WTFPL (http://sam.zoy.org/wtfpl/)
*/

//
// Google Maps loads many JS files asynchronously, so listening just to the first script load
// isn't enough to check if it is ready to be used, another problem is that the regular gmaps script 
// uses document.write, so we need to pass a `callback` parameter to make it not use `document.write` 
// and wait for the callback call.
// <http://code.google.com/apis/maps/documentation/javascript/basics.html#Async>
//
require(['async!http://maps.google.com/maps/api/js?sensor=false!callback'], function(){

	//Google maps is available and all components are ready to use.

	var mapDiv = document.getElementById('map-canvas');
	
	var map = new google.maps.Map(mapDiv, {
		center: new google.maps.LatLng(37.4419, -122.1419),
		zoom: 13,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		navigationControl: true,
		navigationControlOptions: {
			style: google.maps.NavigationControlStyle.SMALL
		}
	});

});

gistfile3.js

/*
* RequireJS Async plugin + JSONP + custom callback name param
* @author Miller Medeiros
* released under the WTFPL (http://sam.zoy.org/wtfpl/)
*/

//
// load a JSONP file which expects an `awesomecallback` parameter to register callback function name
//
require(['async!my_jsonp_file.js!awesomecallback'], function(data){
  console.log(data);
});