How would I use the Bing Maps API with the latest version of RequireJS? The remote script URL is:
http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0
Would I just add a shim like this?
require.config({
/* ... */
paths: {
'Microsoft.Maps': 'http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0'
},
shim: {
'Microsoft.Maps': {
deps: [],
exports: 'Microsoft'
}
}
});
And then to use it in my modules like this:
define(['Microsoft.Maps'], function(Microsoft) {
/* ... */
});
I guess my question is more about how to use namespaced code in general with RequireJS. The docs don't go into any examples of it that I could find.
It turns out that you can do this with the async plugin, like so:
define([
'async!http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0!onscriptload'
], function() {
// Microsoft and Microsoft.Maps will be available here
});
The async! bit tells RequireJS to use the async plugin, and the !onscriptload bit tells it to send the auto-generated callback name in the onscriptload URL parameter. When Bing is done loading all assets, it will send back a JSONP response that calls whatever callback the async plugin provided it in the onscriptload parameter, which then translates into the resources being loaded asynchronously and then made available for your module.
While looking at the documentation regarding RequireJS, I saw this line:
Do not mix CDN loading with shim config in a build. Example scenario: you load jQuery from the CDN but use the shim config to load something like the stock version of Backbone that depends on jQuery. When you do the build, be sure to inline jQuery in the built file and do not load it from the CDN. Otherwise, Backbone will be inlined in the built file and it will execute before the CDN-loaded jQuery will load. This is because the shim config just delays loading of the files until dependencies are loaded, but does not do any auto-wrapping of define. After a build, the dependencies are already inlined, the shim config cannot delay execution of the non-define()'d code until later. define()'d modules do work with CDN loaded code after a build because they properly wrap their source in define factory function that will not execute until dependencies are loaded. So the lesson: shim config is a stop-gap measure for non-modular code, legacy code. define()'d modules are better.
See: http://requirejs.org/docs/api.html#config
Microsoft is loading multiple elements with the first script reference (deffered loading), you should clearly avoid using it in another way through shim as it's more like the CDN loading case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With