loader.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. define("dojo/_base/loader", ["./kernel", "../has", "require", "module", "./json", "./lang", "./array"], function(dojo, has, require, thisModule, json, lang, array) {
  2. // module:
  3. // dojo/_base/lader
  4. // summary:
  5. // This module defines the v1.x synchronous loader API.
  6. // signal the loader in sync mode...
  7. //>>pure-amd
  8. if (!1){
  9. console.error("cannot load the Dojo v1.x loader with a foreign loader");
  10. return 0;
  11. }
  12. var makeErrorToken = function(id){
  13. return {src:thisModule.id, id:id};
  14. },
  15. slashName = function(name){
  16. return name.replace(/\./g, "/");
  17. },
  18. buildDetectRe = /\/\/>>built/,
  19. dojoRequireCallbacks = [],
  20. dojoRequireModuleStack = [],
  21. dojoRequirePlugin = function(mid, require, loaded){
  22. dojoRequireCallbacks.push(loaded);
  23. array.forEach(mid.split(","), function(mid){
  24. var module = getModule(mid, require.module);
  25. dojoRequireModuleStack.push(module);
  26. injectModule(module);
  27. });
  28. checkDojoRequirePlugin();
  29. },
  30. // checkDojoRequirePlugin inspects all of the modules demanded by a dojo/require!<module-list> dependency
  31. // to see if they have arrived. The loader does not release *any* of these modules to be instantiated
  32. // until *all* of these modules are on board, thereby preventing the evaluation of a module with dojo.require's
  33. // that reference modules that are not available.
  34. //
  35. // The algorithm works by traversing the dependency graphs (remember, there can be cycles so they are not trees)
  36. // of each module in the dojoRequireModuleStack array (which contains the list of modules demanded by dojo/require!).
  37. // The moment a single module is discovered that is missing, the algorithm gives up and indicates that not all
  38. // modules are on board. dojo/loadInit! and dojo/require! are ignored because there dependencies are inserted
  39. // directly in dojoRequireModuleStack. For example, if "your/module" module depends on "dojo/require!my/module", then
  40. // *both* "dojo/require!my/module" and "my/module" will be in dojoRequireModuleStack. Obviously, if "my/module"
  41. // is on board, then "dojo/require!my/module" is also satisfied, so the algorithm doesn't check for "dojo/require!my/module".
  42. //
  43. // Note: inserting a dojo/require!<some-module-list> dependency in the dojoRequireModuleStack achieves nothing
  44. // with the current algorithm; however, having such modules present makes it possible to optimize the algorithm
  45. //
  46. // Note: prior versions of this algorithm had an optimization that signaled loaded on dojo/require! dependencies
  47. // individually (rather than waiting for them all to be resolved). The implementation proved problematic with cycles
  48. // and plugins. However, it is possible to reattach that strategy in the future.
  49. // a set from module-id to {undefined | 1 | 0}, where...
  50. // undefined => the module has not been inspected
  51. // 0 => the module or at least one of its dependencies has not arrived
  52. // 1 => the module is a loadInit! or require! plugin resource, or is currently being traversed (therefore, assume
  53. // OK until proven otherwise), or has been completely traversed and all dependencies have arrived
  54. touched,
  55. traverse = function(m){
  56. touched[m.mid] = 1;
  57. for(var t, module, deps = m.deps || [], i= 0; i<deps.length; i++){
  58. module = deps[i];
  59. if(!(t = touched[module.mid])){
  60. if(t===0 || !traverse(module)){
  61. touched[m.mid] = 0;
  62. return false;
  63. }
  64. }
  65. }
  66. return true;
  67. },
  68. checkDojoRequirePlugin = function(){
  69. // initialize the touched hash with easy-to-compute values that help short circuit recursive algorithm;
  70. // recall loadInit/require plugin modules are dependencies of modules in dojoRequireModuleStack...
  71. // which would cause a circular dependency chain that would never be resolved if checked here
  72. // notice all dependencies of any particular loadInit/require plugin module will already
  73. // be checked since those are pushed into dojoRequireModuleStack explicitly by the
  74. // plugin...so if a particular loadInitPlugin module's dependencies are not really
  75. // on board, that *will* be detected elsewhere in the traversal.
  76. var module, mid;
  77. touched = {};
  78. for(mid in modules){
  79. module = modules[mid];
  80. // this could be improved by remembering the result of the regex tests
  81. if(module.executed || module.noReqPluginCheck){
  82. touched[mid] = 1;
  83. }else{
  84. if(module.noReqPluginCheck!==0){
  85. // tag the module as either a loadInit or require plugin or not for future reference
  86. module.noReqPluginCheck = /loadInit\!/.test(mid) || /require\!/.test(mid) ? 1 : 0;
  87. }
  88. if(module.noReqPluginCheck){
  89. touched[mid] = 1;
  90. }else if(module.injected!==arrived){
  91. // not executed, has not arrived, and is not a loadInit or require plugin resource
  92. touched[mid] = 0;
  93. }// else, leave undefined and we'll traverse the dependencies
  94. }
  95. }
  96. for(var t, i = 0, end = dojoRequireModuleStack.length; i<end; i++){
  97. module = dojoRequireModuleStack[i];
  98. if(!(t = touched[module.mid])){
  99. if(t===0 || !traverse(module)){
  100. return;
  101. }
  102. }
  103. }
  104. loaderVars.holdIdle();
  105. var oldCallbacks = dojoRequireCallbacks;
  106. dojoRequireCallbacks = [];
  107. array.forEach(oldCallbacks, function(cb){cb(1);});
  108. loaderVars.releaseIdle();
  109. },
  110. dojoLoadInitPlugin = function(mid, require, loaded){
  111. // mid names a module that defines a "dojo load init" bundle, an object with two properties:
  112. //
  113. // * names: a vector of module ids that give top-level names to define in the lexical scope of def
  114. // * def: a function that contains some some legacy loader API applications
  115. //
  116. // The point of def is to possibly cause some modules to be loaded (but not executed) by dojo/require! where the module
  117. // ids are possibly-determined at runtime. For example, here is dojox.gfx from v1.6 expressed as an AMD module using the dojo/loadInit
  118. // and dojo/require plugins.
  119. //
  120. // // dojox/gfx:
  121. //
  122. // define("*loadInit_12, {
  123. // names:["dojo", "dijit", "dojox"],
  124. // def: function(){
  125. // dojo.loadInit(function(){
  126. // var gfx = lang.getObject("dojox.gfx", true);
  127. //
  128. // //
  129. // // code required to set gfx properties ommitted...
  130. // //
  131. //
  132. // // now use the calculations to include the runtime-dependent module
  133. // dojo.require("dojox.gfx." + gfx.renderer);
  134. // });
  135. // }
  136. // });
  137. //
  138. // define(["dojo", "dojo/loadInit!" + id].concat("dojo/require!dojox/gfx/matric,dojox/gfx/_base"), function(dojo){
  139. // // when this AMD factory function is executed, the following modules are guaranteed downloaded but not executed:
  140. // // "dojox.gfx." + gfx.renderer
  141. // // dojox.gfx.matrix
  142. // // dojox.gfx._base
  143. // dojo.provide("dojo.gfx");
  144. // dojo.require("dojox.gfx.matrix");
  145. // dojo.require("dojox.gfx._base");
  146. // dojo.require("dojox.gfx." + gfx.renderer);
  147. // return lang.getObject("dojo.gfx");
  148. // });
  149. // })();
  150. //
  151. // The idea is to run the legacy loader API with global variables shadowed, which allows these variables to
  152. // be relocated. For example, dojox and dojo could be relocated to different names by giving a packageMap and the code above will
  153. // execute properly (because the plugin below resolves the load init bundle.names module with respect to the module that demanded
  154. // the plugin resource).
  155. //
  156. // Note that the relocation is specified in the runtime configuration; relocated names need not be set at build-time.
  157. //
  158. // Warning: this is not the best way to express dojox.gfx as and AMD module. In fact, the module has been properly converted in
  159. // v1.7. However, this technique allows the builder to convert legacy modules into AMD modules and guarantee the codepath is the
  160. // same in the converted AMD module.
  161. require([mid], function(bundle){
  162. // notice how names is resolved with respect to the module that demanded the plugin resource
  163. require(bundle.names, function(){
  164. // bring the bundle names into scope
  165. for(var scopeText = "", args= [], i = 0; i<arguments.length; i++){
  166. scopeText+= "var " + bundle.names[i] + "= arguments[" + i + "]; ";
  167. args.push(arguments[i]);
  168. }
  169. eval(scopeText);
  170. var callingModule = require.module,
  171. deps = [],
  172. hold = {},
  173. requireList = [],
  174. p,
  175. syncLoaderApi = {
  176. provide:function(moduleName){
  177. // mark modules that arrive consequent to multiple provides in this module as arrived since they can't be injected
  178. moduleName = slashName(moduleName);
  179. var providedModule = getModule(moduleName, callingModule);
  180. if(providedModule!==callingModule){
  181. setArrived(providedModule);
  182. }
  183. },
  184. require:function(moduleName, omitModuleCheck){
  185. moduleName = slashName(moduleName);
  186. omitModuleCheck && (getModule(moduleName, callingModule).result = nonmodule);
  187. requireList.push(moduleName);
  188. },
  189. requireLocalization:function(moduleName, bundleName, locale){
  190. // since we're going to need dojo/i8n, add it to deps if not already there
  191. deps.length || (deps = ["dojo/i18n"]);
  192. // figure out if the bundle is xdomain; if so, add it to the depsSet
  193. locale = (locale || dojo.locale).toLowerCase();
  194. moduleName = slashName(moduleName) + "/nls/" + (/root/i.test(locale) ? "" : locale + "/") + slashName(bundleName);
  195. if(getModule(moduleName, callingModule).isXd){
  196. deps.push("dojo/i18n!" + moduleName);
  197. }// else the bundle will be loaded synchronously when the module is evaluated
  198. },
  199. loadInit:function(f){
  200. f();
  201. }
  202. };
  203. // hijack the correct dojo and apply bundle.def
  204. try{
  205. for(p in syncLoaderApi){
  206. hold[p] = dojo[p];
  207. dojo[p] = syncLoaderApi[p];
  208. }
  209. bundle.def.apply(null, args);
  210. }catch(e){
  211. signal("error", [makeErrorToken("failedDojoLoadInit"), e]);
  212. }finally{
  213. for(p in syncLoaderApi){
  214. dojo[p] = hold[p];
  215. }
  216. }
  217. // requireList is the list of modules that need to be downloaded but not executed before the callingModule can be executed
  218. requireList.length && deps.push("dojo/require!" + requireList.join(","));
  219. dojoRequireCallbacks.push(loaded);
  220. array.forEach(requireList, function(mid){
  221. var module = getModule(mid, require.module);
  222. dojoRequireModuleStack.push(module);
  223. injectModule(module);
  224. });
  225. checkDojoRequirePlugin();
  226. });
  227. });
  228. },
  229. extractApplication = function(
  230. text, // the text to search
  231. startSearch, // the position in text to start looking for the closing paren
  232. startApplication // the position in text where the function application expression starts
  233. ){
  234. // find end of the call by finding the matching end paren
  235. // Warning: as usual, this will fail in the presense of unmatched right parans contained in strings, regexs, or unremoved comments
  236. var parenRe = /\(|\)/g,
  237. matchCount = 1,
  238. match;
  239. parenRe.lastIndex = startSearch;
  240. while((match = parenRe.exec(text))){
  241. if(match[0] == ")"){
  242. matchCount -= 1;
  243. }else{
  244. matchCount += 1;
  245. }
  246. if(matchCount == 0){
  247. break;
  248. }
  249. }
  250. if(matchCount != 0){
  251. throw "unmatched paren around character " + parenRe.lastIndex + " in: " + text;
  252. }
  253. //Put the master matching string in the results.
  254. return [dojo.trim(text.substring(startApplication, parenRe.lastIndex))+";\n", parenRe.lastIndex];
  255. },
  256. // the following regex is taken from 1.6. It is a very poor technique to remove comments and
  257. // will fail in some cases; for example, consider the code...
  258. //
  259. // var message = "Category-1 */* Category-2";
  260. //
  261. // The regex that follows will see a /* comment and trash the code accordingly. In fact, there are all
  262. // kinds of cases like this with strings and regexs that will cause this design to fail miserably.
  263. //
  264. // Alternative regex designs exist that will result in less-likely failures, but will still fail in many cases.
  265. // The only solution guaranteed 100% correct is to parse the code and that seems overkill for this
  266. // backcompat/unbuilt-xdomain layer. In the end, since it's been this way for a while, we won't change it.
  267. // See the opening paragraphs of Chapter 7 or ECME-262 which describes the lexical abiguity further.
  268. removeCommentRe = /(\/\*([\s\S]*?)\*\/|\/\/(.*)$)/mg,
  269. syncLoaderApiRe = /(^|\s)dojo\.(loadInit|require|provide|requireLocalization|requireIf|requireAfterIf|platformRequire)\s*\(/mg,
  270. amdLoaderApiRe = /(^|\s)(require|define)\s*\(/m,
  271. extractLegacyApiApplications = function(text, noCommentText){
  272. // scan the noCommentText for any legacy loader API applications. Copy such applications into result (this is
  273. // used by the builder). Move dojo.loadInit applications to loadInitApplications string. Copy all other applications
  274. // to otherApplications string. If no applications were found, return 0, signalling an AMD module. Otherwise, return
  275. // loadInitApplications + otherApplications. Fixup text by replacing
  276. //
  277. // dojo.loadInit(// etc...
  278. //
  279. // with
  280. //
  281. // \n 0 && dojo.loadInit(// etc...
  282. //
  283. // Which results in the dojo.loadInit from *not* being applied. This design goes a long way towards protecting the
  284. // code from an over-agressive removeCommentRe. However...
  285. //
  286. // WARNING: the removeCommentRe will cause an error if a detected comment removes all or part of a legacy-loader application
  287. // that is not in a comment.
  288. var match, startSearch, startApplication, application,
  289. loadInitApplications = [],
  290. otherApplications = [],
  291. allApplications = [];
  292. // noCommentText may be provided by a build app with comments extracted by a better method than regex (hopefully)
  293. noCommentText = noCommentText || text.replace(removeCommentRe, function(match){
  294. // remove iff the detected comment has text that looks like a sync loader API application; this helps by
  295. // removing as little as possible, minimizing the changes the janky regex will kill the module
  296. syncLoaderApiRe.lastIndex = amdLoaderApiRe.lastIndex = 0;
  297. return (syncLoaderApiRe.test(match) || amdLoaderApiRe.test(match)) ? "" : match;
  298. });
  299. // find and extract all dojo.loadInit applications
  300. while((match = syncLoaderApiRe.exec(noCommentText))){
  301. startSearch = syncLoaderApiRe.lastIndex;
  302. startApplication = startSearch - match[0].length;
  303. application = extractApplication(noCommentText, startSearch, startApplication);
  304. if(match[2]=="loadInit"){
  305. loadInitApplications.push(application[0]);
  306. }else{
  307. otherApplications.push(application[0]);
  308. }
  309. syncLoaderApiRe.lastIndex = application[1];
  310. }
  311. allApplications = loadInitApplications.concat(otherApplications);
  312. if(allApplications.length || !amdLoaderApiRe.test(noCommentText)){
  313. // either there were some legacy loader API applications or there were no AMD API applications
  314. return [text.replace(/(^|\s)dojo\.loadInit\s*\(/g, "\n0 && dojo.loadInit("), allApplications.join(""), allApplications];
  315. }else{
  316. // legacy loader API *was not* detected and AMD API *was* detected; therefore, assume it's an AMD module
  317. return 0;
  318. }
  319. },
  320. transformToAmd = function(module, text){
  321. // This is roughly the equivalent of dojo._xdCreateResource in 1.6-; however, it expresses a v1.6- dojo
  322. // module in terms of AMD define instead of creating the dojo proprietary xdomain module expression.
  323. // The module could have originated from several sources:
  324. //
  325. // * amd require() a module, e.g., require(["my/module"])
  326. // * amd require() a nonmodule, e.g., require(["my/resource.js"')
  327. // * amd define() deps vector (always a module)
  328. // * dojo.require() a module, e.g. dojo.require("my.module")
  329. // * dojo.require() a nonmodule, e.g., dojo.require("my.module", true)
  330. // * dojo.requireIf/requireAfterIf/platformRequire a module
  331. //
  332. // The module is scanned for legacy loader API applications; if none are found, then assume the module is an
  333. // AMD module and return 0. Otherwise, a synthetic dojo/loadInit plugin resource is created and the module text
  334. // is rewritten as an AMD module with the single dependency of this synthetic resource. When the dojo/loadInit
  335. // plugin loaded the synthetic resource, it will cause all dojo.loadInit's to be executed, find all dojo.require's
  336. // (either directly consequent to dojo.require or indirectly consequent to dojo.require[After]If or
  337. // dojo.platformRequire, and finally cause loading of all dojo.required modules with the dojo/require plugin. Thus,
  338. // when the dojo/loadInit plugin reports it has been loaded, all modules required by the given module are guaranteed
  339. // loaded (but not executed). This then allows the module to execute it's code path without interupts, thereby
  340. // following the synchronous code path.
  341. var extractResult, id, names = [], namesAsStrings = [];
  342. if(buildDetectRe.test(text) || !(extractResult = extractLegacyApiApplications(text))){
  343. // buildDetectRe.test(text) => a built module, always AMD
  344. // extractResult==0 => no sync API
  345. return 0;
  346. }
  347. // manufacture a synthetic module id that can never be a real mdule id (just like require does)
  348. id = module.mid + "-*loadInit";
  349. // construct the dojo/loadInit names vector which causes any relocated names to be defined as lexical variables under their not-relocated name
  350. // the dojo/loadInit plugin assumes the first name in names is "dojo"
  351. for(var p in getModule("dojo", module).result.scopeMap){
  352. names.push(p);
  353. namesAsStrings.push('"' + p + '"');
  354. }
  355. // rewrite the module as a synthetic dojo/loadInit plugin resource + the module expressed as an AMD module that depends on this synthetic resource
  356. return "// xdomain rewrite of " + module.path + "\n" +
  357. "define('" + id + "',{\n" +
  358. "\tnames:" + dojo.toJson(names) + ",\n" +
  359. "\tdef:function(" + names.join(",") + "){" + extractResult[1] + "}" +
  360. "});\n\n" +
  361. "define(" + dojo.toJson(names.concat(["dojo/loadInit!"+id])) + ", function(" + names.join(",") + "){\n" + extractResult[0] + "});";
  362. },
  363. loaderVars = require.initSyncLoader(dojoRequirePlugin, checkDojoRequirePlugin, transformToAmd),
  364. sync =
  365. loaderVars.sync,
  366. xd =
  367. loaderVars.xd,
  368. arrived =
  369. loaderVars.arrived,
  370. nonmodule =
  371. loaderVars.nonmodule,
  372. executing =
  373. loaderVars.executing,
  374. executed =
  375. loaderVars.executed,
  376. syncExecStack =
  377. loaderVars.syncExecStack,
  378. modules =
  379. loaderVars.modules,
  380. execQ =
  381. loaderVars.execQ,
  382. getModule =
  383. loaderVars.getModule,
  384. injectModule =
  385. loaderVars.injectModule,
  386. setArrived =
  387. loaderVars.setArrived,
  388. signal =
  389. loaderVars.signal,
  390. finishExec =
  391. loaderVars.finishExec,
  392. execModule =
  393. loaderVars.execModule,
  394. getLegacyMode =
  395. loaderVars.getLegacyMode;
  396. dojo.provide = function(mid){
  397. var executingModule = syncExecStack[0],
  398. module = lang.mixin(getModule(slashName(mid), require.module), {
  399. executed:executing,
  400. result:lang.getObject(mid, true)
  401. });
  402. setArrived(module);
  403. if(executingModule){
  404. (executingModule.provides || (executingModule.provides = [])).push(function(){
  405. module.result = lang.getObject(mid);
  406. delete module.provides;
  407. module.executed!==executed && finishExec(module);
  408. });
  409. }// else dojo.provide called not consequent to loading; therefore, give up trying to publish module value to loader namespace
  410. return module.result;
  411. };
  412. has.add("config-publishRequireResult", 1, 0, 0);
  413. dojo.require = function(moduleName, omitModuleCheck) {
  414. // summary:
  415. // loads a Javascript module from the appropriate URI
  416. //
  417. // moduleName: String
  418. // module name to load, using periods for separators,
  419. // e.g. "dojo.date.locale". Module paths are de-referenced by dojo's
  420. // internal mapping of locations to names and are disambiguated by
  421. // longest prefix. See `dojo.registerModulePath()` for details on
  422. // registering new modules.
  423. //
  424. // omitModuleCheck: Boolean?
  425. // if `true`, omitModuleCheck skips the step of ensuring that the
  426. // loaded file actually defines the symbol it is referenced by.
  427. // For example if it called as `dojo.require("a.b.c")` and the
  428. // file located at `a/b/c.js` does not define an object `a.b.c`,
  429. // and exception will be throws whereas no exception is raised
  430. // when called as `dojo.require("a.b.c", true)`
  431. //
  432. // description:
  433. // Modules are loaded via dojo.require by using one of two loaders: the normal loader
  434. // and the xdomain loader. The xdomain loader is used when dojo was built with a
  435. // custom build that specified loader=xdomain and the module lives on a modulePath
  436. // that is a whole URL, with protocol and a domain. The versions of Dojo that are on
  437. // the Google and AOL CDNs use the xdomain loader.
  438. //
  439. // If the module is loaded via the xdomain loader, it is an asynchronous load, since
  440. // the module is added via a dynamically created script tag. This
  441. // means that dojo.require() can return before the module has loaded. However, this
  442. // should only happen in the case where you do dojo.require calls in the top-level
  443. // HTML page, or if you purposely avoid the loader checking for dojo.require
  444. // dependencies in your module by using a syntax like dojo["require"] to load the module.
  445. //
  446. // Sometimes it is useful to not have the loader detect the dojo.require calls in the
  447. // module so that you can dynamically load the modules as a result of an action on the
  448. // page, instead of right at module load time.
  449. //
  450. // Also, for script blocks in an HTML page, the loader does not pre-process them, so
  451. // it does not know to download the modules before the dojo.require calls occur.
  452. //
  453. // So, in those two cases, when you want on-the-fly module loading or for script blocks
  454. // in the HTML page, special care must be taken if the dojo.required code is loaded
  455. // asynchronously. To make sure you can execute code that depends on the dojo.required
  456. // modules, be sure to add the code that depends on the modules in a dojo.addOnLoad()
  457. // callback. dojo.addOnLoad waits for all outstanding modules to finish loading before
  458. // executing.
  459. //
  460. // This type of syntax works with both xdomain and normal loaders, so it is good
  461. // practice to always use this idiom for on-the-fly code loading and in HTML script
  462. // blocks. If at some point you change loaders and where the code is loaded from,
  463. // it will all still work.
  464. //
  465. // More on how dojo.require
  466. // `dojo.require("A.B")` first checks to see if symbol A.B is
  467. // defined. If it is, it is simply returned (nothing to do).
  468. //
  469. // If it is not defined, it will look for `A/B.js` in the script root
  470. // directory.
  471. //
  472. // `dojo.require` throws an exception if it cannot find a file
  473. // to load, or if the symbol `A.B` is not defined after loading.
  474. //
  475. // It returns the object `A.B`, but note the caveats above about on-the-fly loading and
  476. // HTML script blocks when the xdomain loader is loading a module.
  477. //
  478. // `dojo.require()` does nothing about importing symbols into
  479. // the current namespace. It is presumed that the caller will
  480. // take care of that.
  481. //
  482. // example:
  483. // To use dojo.require in conjunction with dojo.ready:
  484. //
  485. // | dojo.require("foo");
  486. // | dojo.require("bar");
  487. // | dojo.addOnLoad(function(){
  488. // | //you can now safely do something with foo and bar
  489. // | });
  490. //
  491. // example:
  492. // For example, to import all symbols into a local block, you might write:
  493. //
  494. // | with (dojo.require("A.B")) {
  495. // | ...
  496. // | }
  497. //
  498. // And to import just the leaf symbol to a local variable:
  499. //
  500. // | var B = dojo.require("A.B");
  501. // | ...
  502. //
  503. // returns:
  504. // the required namespace object
  505. function doRequire(mid, omitModuleCheck){
  506. var module = getModule(slashName(mid), require.module);
  507. if(syncExecStack.length && syncExecStack[0].finish){
  508. // switched to async loading in the middle of evaluating a legacy module; stop
  509. // applying dojo.require so the remaining dojo.requires are applied in order
  510. syncExecStack[0].finish.push(mid);
  511. return undefined;
  512. }
  513. // recall module.executed has values {0, executing, executed}; therefore, truthy indicates executing or executed
  514. if(module.executed){
  515. return module.result;
  516. }
  517. omitModuleCheck && (module.result = nonmodule);
  518. var currentMode = getLegacyMode();
  519. // recall, in sync mode to inject is to *eval* the module text
  520. // if the module is a legacy module, this is the same as executing
  521. // but if the module is an AMD module, this means defining, not executing
  522. injectModule(module);
  523. // the inject may have changed the mode
  524. currentMode = getLegacyMode();
  525. // in sync mode to dojo.require is to execute
  526. if(module.executed!==executed && module.injected===arrived){
  527. // the module was already here before injectModule was called probably finishing up a xdomain
  528. // load, but maybe a module given to the loader directly rather than having the loader retrieve it
  529. loaderVars.holdIdle();
  530. execModule(module);
  531. loaderVars.releaseIdle();
  532. }
  533. if(module.executed){
  534. return module.result;
  535. }
  536. if(currentMode==sync){
  537. // the only way to get here is in sync mode and dojo.required a module that
  538. // * was loaded async in the injectModule application a few lines up
  539. // * was an AMD module that had deps that are being loaded async and therefore couldn't execute
  540. if(module.cjs){
  541. // the module was an AMD module; unshift, not push, which causes the current traversal to be reattempted from the top
  542. execQ.unshift(module);
  543. }else{
  544. // the module was a legacy module
  545. syncExecStack.length && (syncExecStack[0].finish= [mid]);
  546. }
  547. }else{
  548. // the loader wasn't in sync mode on entry; probably async mode; therefore, no expectation of getting
  549. // the module value synchronously; make sure it gets executed though
  550. execQ.push(module);
  551. }
  552. return undefined;
  553. }
  554. var result = doRequire(moduleName, omitModuleCheck);
  555. if(has("config-publishRequireResult") && !lang.exists(moduleName) && result!==undefined){
  556. lang.setObject(moduleName, result);
  557. }
  558. return result;
  559. };
  560. dojo.loadInit = function(f) {
  561. f();
  562. };
  563. dojo.registerModulePath = function(/*String*/moduleName, /*String*/prefix){
  564. // summary:
  565. // Maps a module name to a path
  566. // description:
  567. // An unregistered module is given the default path of ../[module],
  568. // relative to Dojo root. For example, module acme is mapped to
  569. // ../acme. If you want to use a different module name, use
  570. // dojo.registerModulePath.
  571. // example:
  572. // If your dojo.js is located at this location in the web root:
  573. // | /myapp/js/dojo/dojo/dojo.js
  574. // and your modules are located at:
  575. // | /myapp/js/foo/bar.js
  576. // | /myapp/js/foo/baz.js
  577. // | /myapp/js/foo/thud/xyzzy.js
  578. // Your application can tell Dojo to locate the "foo" namespace by calling:
  579. // | dojo.registerModulePath("foo", "../../foo");
  580. // At which point you can then use dojo.require() to load the
  581. // modules (assuming they provide() the same things which are
  582. // required). The full code might be:
  583. // | <script type="text/javascript"
  584. // | src="/myapp/js/dojo/dojo/dojo.js"></script>
  585. // | <script type="text/javascript">
  586. // | dojo.registerModulePath("foo", "../../foo");
  587. // | dojo.require("foo.bar");
  588. // | dojo.require("foo.baz");
  589. // | dojo.require("foo.thud.xyzzy");
  590. // | </script>
  591. var paths = {};
  592. paths[moduleName.replace(/\./g, "/")] = prefix;
  593. require({paths:paths});
  594. };
  595. dojo.platformRequire = function(/*Object*/modMap){
  596. // summary:
  597. // require one or more modules based on which host environment
  598. // Dojo is currently operating in
  599. // description:
  600. // This method takes a "map" of arrays which one can use to
  601. // optionally load dojo modules. The map is indexed by the
  602. // possible dojo.name_ values, with two additional values:
  603. // "default" and "common". The items in the "default" array will
  604. // be loaded if none of the other items have been choosen based on
  605. // dojo.name_, set by your host environment. The items in the
  606. // "common" array will *always* be loaded, regardless of which
  607. // list is chosen.
  608. // example:
  609. // | dojo.platformRequire({
  610. // | browser: [
  611. // | "foo.sample", // simple module
  612. // | "foo.test",
  613. // | ["foo.bar.baz", true] // skip object check in _loadModule (dojo.require)
  614. // | ],
  615. // | default: [ "foo.sample._base" ],
  616. // | common: [ "important.module.common" ]
  617. // | });
  618. var result = (modMap.common || []).concat(modMap[dojo._name] || modMap["default"] || []),
  619. temp;
  620. while(result.length){
  621. if(lang.isArray(temp = result.shift())){
  622. dojo.require.apply(dojo, temp);
  623. }else{
  624. dojo.require(temp);
  625. }
  626. }
  627. };
  628. dojo.requireIf = dojo.requireAfterIf = function(/*Boolean*/ condition, /*String*/ moduleName, /*Boolean?*/omitModuleCheck){
  629. // summary:
  630. // If the condition is true then call `dojo.require()` for the specified
  631. // resource
  632. //
  633. // example:
  634. // | dojo.requireIf(dojo.isBrowser, "my.special.Module");
  635. if(condition){
  636. dojo.require(moduleName, omitModuleCheck);
  637. }
  638. };
  639. dojo.requireLocalization = function(/*String*/moduleName, /*String*/bundleName, /*String?*/locale){
  640. require(["../i18n"], function(i18n){
  641. i18n.getLocalization(moduleName, bundleName, locale);
  642. });
  643. };
  644. return {
  645. extractLegacyApiApplications:extractLegacyApiApplications,
  646. require:loaderVars.dojoRequirePlugin,
  647. loadInit:dojoLoadInitPlugin
  648. };
  649. });