async.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /** @license
  2. * RequireJS plugin for async dependency load like JSONP and Google Maps
  3. * Author: Miller Medeiros
  4. * Version: 0.1.2 (2014/02/24)
  5. * Released under the MIT license
  6. */
  7. define(function(){
  8. var DEFAULT_PARAM_NAME = 'callback',
  9. _uid = 0;
  10. function injectScript(src){
  11. var s, t;
  12. s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = src;
  13. t = document.getElementsByTagName('script')[0]; t.parentNode.insertBefore(s,t);
  14. }
  15. function formatUrl(name, id){
  16. var paramRegex = /!(.+)/,
  17. url = name.replace(paramRegex, ''),
  18. param = (paramRegex.test(name))? name.replace(/.+!/, '') : DEFAULT_PARAM_NAME;
  19. url += (url.indexOf('?') < 0)? '?' : '&';
  20. return url + param +'='+ id;
  21. }
  22. function uid() {
  23. _uid += 1;
  24. return '__async_req_'+ _uid +'__';
  25. }
  26. return{
  27. load : function(name, req, onLoad, config){
  28. if(config.isBuild){
  29. onLoad(null); //avoid errors on the optimizer
  30. }else{
  31. var id = uid();
  32. //create a global variable that stores onLoad so callback
  33. //function can define new module after async load
  34. window[id] = onLoad;
  35. injectScript(formatUrl(req.toUrl(name), id));
  36. }
  37. }
  38. };
  39. });