Search code examples
javascriptrequirejsamd

RequireJS - Own module with two ways loading


I'm trying to create a module that can be loaded asynchronously (AMD) and via HTML script tag. I added this construction to my module (I took it from jQuery source code):

if ( typeof define === "function" && define.amd ) { 
    define( "mymodule", ['googlemaps'], function(google) {
       return myModule; 
    }); 
}

myModule = function() {
    // here code uses "google" 
}

My module depends on Google Maps API so if I load my module via HTML script tag it works. But if my module was loaded asynchronously variable "google" only available in "define" block. Are there any ways to pass this variable to global scope (for my module file)?


Solution

  • (function(global, factory) {
      if (typeof define === 'function' && define.amd) { // requirejs
        return define(['googlemaps'], factory);
      } else if (typeof exports === 'object') {    // nodejs
        return module.exports = factory(require('googlemaps'));
      } else {  // html
        return global['Odysseus'] = factory(global['googlemaps']);
      }
    })(this, function(GoogleAPI) {
        ...
        return myModule; 
    });