├── ModularDemo
├── Scripts1
│ ├── main.js
│ ├── dataservice.js
│ └── alerter.js
├── packages.config
├── Scripts2
│ ├── main.js
│ ├── dataservice.js
│ ├── alerter.js
│ └── require.js
├── Scripts3
│ ├── dataservice.js
│ ├── main.js
│ ├── alerter.js
│ └── require.js
├── Web.config
├── index2.html
├── index1.html
├── index3.html
├── Web.Debug.config
├── Web.Release.config
├── Properties
│ └── AssemblyInfo.cs
├── Require.JS - LICENSE.txt
└── ModularDemo.csproj
├── .gitignore
├── ModularDemo.sln
├── flush.cmd
└── README.md
/ModularDemo/Scripts1/main.js:
--------------------------------------------------------------------------------
1 | (function (alerter) {
2 |
3 | alerter.showMessage();
4 |
5 | })(alerter);
--------------------------------------------------------------------------------
/ModularDemo/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/ModularDemo/Scripts1/dataservice.js:
--------------------------------------------------------------------------------
1 | var dataservice = (function () {
2 | var
3 | msg = 'Welcome to Code Camp',
4 | getMessage = function () {
5 | return msg;
6 | };
7 |
8 | return {
9 | getMessage: getMessage
10 | };
11 | })();
--------------------------------------------------------------------------------
/ModularDemo/Scripts2/main.js:
--------------------------------------------------------------------------------
1 | (function () {
2 |
3 | requirejs.config(
4 | {
5 | baseUrl: 'scripts2',
6 | }
7 | );
8 |
9 | require(['alerter'],
10 | function (alerter) {
11 | alerter.showMessage();
12 | });
13 | })();
--------------------------------------------------------------------------------
/ModularDemo/Scripts2/dataservice.js:
--------------------------------------------------------------------------------
1 | define('dataservice', [],
2 | function () {
3 | var
4 | msg = 'Welcome to Code Camp',
5 | getMessage = function () {
6 | return msg;
7 | };
8 |
9 | return {
10 | getMessage: getMessage
11 | };
12 | });
--------------------------------------------------------------------------------
/ModularDemo/Scripts3/dataservice.js:
--------------------------------------------------------------------------------
1 | define('dataservice', [],
2 | function () {
3 | var
4 | msg = 'Welcome to Code Camp',
5 | getMessage = function () {
6 | return msg;
7 | };
8 |
9 | return {
10 | getMessage: getMessage
11 | };
12 | });
--------------------------------------------------------------------------------
/ModularDemo/Scripts1/alerter.js:
--------------------------------------------------------------------------------
1 | var alerter = (function (dataservice) {
2 | var
3 | name = 'John',
4 | showMessage = function () {
5 | var msg = dataservice.getMessage();
6 | alert(msg + ', ' + name);
7 | };
8 |
9 | return {
10 | showMessage: showMessage
11 | };
12 | })(dataservice);
--------------------------------------------------------------------------------
/ModularDemo/Scripts3/main.js:
--------------------------------------------------------------------------------
1 | (function () {
2 |
3 | requirejs.config(
4 | {
5 | baseUrl: 'scripts3',
6 | paths: {
7 | 'jquery': 'jquery-1.7.2'
8 | }
9 | }
10 | );
11 |
12 | require(['alerter'],
13 | function (alerter) {
14 | alerter.showMessage();
15 | });
16 | })();
--------------------------------------------------------------------------------
/ModularDemo/Web.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/ModularDemo/Scripts2/alerter.js:
--------------------------------------------------------------------------------
1 | define('alerter',
2 | ['dataservice'],
3 | function (dataservice) {
4 |
5 | var
6 | name = 'John',
7 | showMessage = function () {
8 | var msg = dataservice.getMessage();
9 | alert(msg + ', ' + name);
10 | };
11 |
12 | return {
13 | showMessage: showMessage
14 | };
15 | });
--------------------------------------------------------------------------------
/ModularDemo/Scripts3/alerter.js:
--------------------------------------------------------------------------------
1 | define('alerter',
2 | ['jquery', 'dataservice'],
3 | function ($, dataservice) {
4 |
5 | var
6 | name = 'John',
7 | showMessage = function () {
8 | var msg = dataservice.getMessage();
9 | //alert(msg + ', ' + name);
10 | $('#message').text(msg + ', ' + name);
11 | };
12 |
13 | return {
14 | showMessage: showMessage
15 | };
16 | });
--------------------------------------------------------------------------------
/ModularDemo/index2.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Modular Demo 2
5 |
6 |
7 |
8 |
Modular Demo 2: with RequireJS
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/ModularDemo/index1.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Modular Demo 1
5 |
6 |
7 |
8 |
Modular Demo 1: no DI
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/ModularDemo/index3.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Modular Demo 3
5 |
6 |
7 |
8 |
Modular Demo 3: with RequireJS loading jQuery
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # Ignore Visual Studio Project #
3 | ###################
4 | *.user
5 | *.gpState
6 | *.suo
7 | bin*
8 | obj*
9 | /packages
10 |
11 |
12 | # Compiled source #
13 | ###################
14 | *.com
15 | *.class
16 | *.dll
17 | *.exe
18 | *.o
19 | *.so
20 |
21 | # Packages #
22 | ############
23 | # it's better to unpack these files and commit the raw source
24 | # git has its own built in compression methods
25 | *.7z
26 | *.dmg
27 | *.gz
28 | *.iso
29 | *.jar
30 | *.rar
31 | *.tar
32 | *.xap
33 | *.zip
34 |
35 | # Logs and databases #
36 | ######################
37 | *.log
38 | *.sql
39 | *.sqlite
40 | *.sdf
41 |
42 | # OS generated files #
43 | ######################
44 | .DS_Store*
45 | ehthumbs.db
46 | Icon?
47 | Thumbs.db
48 | /CodeCamper.Web/Content/hans_fj
49 | /CodeCamper.Web/Properties/PublishProfiles/Cytanium.pubxml
--------------------------------------------------------------------------------
/ModularDemo.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2012
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModularDemo", "ModularDemo\ModularDemo.csproj", "{3B596E09-8C54-4C34-9DFE-D4BD84DE8908}"
5 | EndProject
6 | Global
7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
8 | Debug|Any CPU = Debug|Any CPU
9 | Release|Any CPU = Release|Any CPU
10 | EndGlobalSection
11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
12 | {3B596E09-8C54-4C34-9DFE-D4BD84DE8908}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13 | {3B596E09-8C54-4C34-9DFE-D4BD84DE8908}.Debug|Any CPU.Build.0 = Debug|Any CPU
14 | {3B596E09-8C54-4C34-9DFE-D4BD84DE8908}.Release|Any CPU.ActiveCfg = Release|Any CPU
15 | {3B596E09-8C54-4C34-9DFE-D4BD84DE8908}.Release|Any CPU.Build.0 = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(SolutionProperties) = preSolution
18 | HideSolutionNode = FALSE
19 | EndGlobalSection
20 | EndGlobal
21 |
--------------------------------------------------------------------------------
/flush.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 |
3 | rmdir ConsoleServer /s /q
4 |
5 | for /R %%i in (.) do rmdir "%%i\Debug" /s /q
6 | for /R %%i in (.) do rmdir "%%i\Release" /s /q
7 | for /R %%i in (.) do rmdir "%%i\obj" /s /q
8 | for /R %%i in (.) do rmdir "%%i\bin" /s /q
9 | for /R %%i in (.) do rmdir "%%i\TestShadowCopy" /s /q
10 | for /R %%i in (.) do rmdir "%%i\TestResults" /s /q
11 |
12 | REM FOR /F "tokens=*" %%G IN ('DIR /B /S /AH *.suo') DO del "%%G" /AH
13 | REM FOR /F "tokens=*" %%G IN ('DIR /B /S *.user') DO del "%%G"
14 | FOR /F "tokens=*" %%G IN ('DIR /B /S *.gpState') DO del "%%G"
15 | FOR /F "tokens=*" %%G IN ('DIR /B /S *.xap') DO del "%%G"
16 |
17 | FOR /F "tokens=*" %%G IN ('DIR /B /S DebugLog*') DO del "%%G"
18 | FOR /F "tokens=*" %%G IN ('DIR /B /S *.bak.*.orm') DO del "%%G"
19 |
20 | FOR /F "tokens=*" %%G IN ('DIR /B /S *.incr') DO del "%%G"
21 | REM FOR /F "tokens=*" %%G IN ('DIR /B /S *.pdb') DO del "%%G"
22 | FOR /F "tokens=*" %%G IN ('DIR /B /S *.aqt') DO del "%%G"
23 | FOR /F "tokens=*" %%G IN ('DIR /B /S *.msi') DO del "%%G"
24 | FOR /F "tokens=*" %%G IN ('DIR /B /S *.tmp') DO del "%%G"
25 |
26 |
27 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | kis-requirejs-demo
2 | ==================
3 |
4 | Keep It Simple RequireJS Demo. Shows simple demo of how to use require.js.
5 |
6 | ##Overview
7 | This demo contains 2 separate html files, each with their own scripts folder. One example demonstrates how to write the code without require.js. The other shows how to add require.js. The purpose is to explain how to use require.js for dependency resolution.
8 |
9 |
10 | ##Without RequireJS
11 | The first example (index1.html) has 3 JavaScript files using the Revealing Module Pattern (Module Pattern works fine too). The dependencies are as follows:
12 |
13 | - main.js depends on alerter.js
14 | - alerter.js depends on daataservice.js
15 |
16 | Load order is important here, and can easily be broken.
17 |
18 | ##With RequireJS
19 | The second example (index2.html) uses require.js to load the scripts. It solves the problem and has these roles:
20 |
21 | - starts with a kickoff script (main.js)
22 | - loads therest of the scripts as they are needed (when dependencies call on them)
23 |
24 | ##With RequireJS and 3rd Party Dependencies
25 | The third example (index3.html) uses require.js to load the scripts while jquery is also introduced as a dependency.
26 |
27 |
28 | ##More
29 | Related topics: Dependency Injection (DI), Revealing Module Pattern, Module Pattern, Immediately Invoked Function Execution (IIFE), and Service Locator Pattern
--------------------------------------------------------------------------------
/ModularDemo/Web.Debug.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
17 |
18 |
29 |
30 |
--------------------------------------------------------------------------------
/ModularDemo/Web.Release.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
17 |
18 |
19 |
30 |
31 |
--------------------------------------------------------------------------------
/ModularDemo/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ModularDemo")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ModularDemo")]
13 | [assembly: AssemblyCopyright("Copyright © 2012")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("f37c3618-88ba-411f-a340-9119b55f5e6d")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Revision and Build Numbers
33 | // by using the '*' as shown below:
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
36 |
--------------------------------------------------------------------------------
/ModularDemo/Require.JS - LICENSE.txt:
--------------------------------------------------------------------------------
1 | RequireJS is released under two licenses: new BSD, and MIT. You may pick the
2 | license that best suits your development needs. The text of both licenses are
3 | provided below.
4 |
5 |
6 | The "New" BSD License:
7 | ----------------------
8 |
9 | Copyright (c) 2010-2011, The Dojo Foundation
10 | All rights reserved.
11 |
12 | Redistribution and use in source and binary forms, with or without
13 | modification, are permitted provided that the following conditions are met:
14 |
15 | * Redistributions of source code must retain the above copyright notice, this
16 | list of conditions and the following disclaimer.
17 | * Redistributions in binary form must reproduce the above copyright notice,
18 | this list of conditions and the following disclaimer in the documentation
19 | and/or other materials provided with the distribution.
20 | * Neither the name of the Dojo Foundation nor the names of its contributors
21 | may be used to endorse or promote products derived from this software
22 | without specific prior written permission.
23 |
24 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
28 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 |
35 |
36 |
37 | MIT License
38 | -----------
39 |
40 | Copyright (c) 2010-2011, The Dojo Foundation
41 |
42 | Permission is hereby granted, free of charge, to any person obtaining a copy
43 | of this software and associated documentation files (the "Software"), to deal
44 | in the Software without restriction, including without limitation the rights
45 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
46 | copies of the Software, and to permit persons to whom the Software is
47 | furnished to do so, subject to the following conditions:
48 |
49 | The above copyright notice and this permission notice shall be included in
50 | all copies or substantial portions of the Software.
51 |
52 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
54 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
55 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
56 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
57 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
58 | THE SOFTWARE.
59 |
--------------------------------------------------------------------------------
/ModularDemo/ModularDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 |
8 |
9 | 2.0
10 | {3B596E09-8C54-4C34-9DFE-D4BD84DE8908}
11 | {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}
12 | Library
13 | Properties
14 | ModularDemo
15 | ModularDemo
16 | v4.5
17 | true
18 |
19 |
20 |
21 |
22 |
23 |
24 | true
25 | full
26 | false
27 | bin\
28 | DEBUG;TRACE
29 | prompt
30 | 4
31 |
32 |
33 | pdbonly
34 | true
35 | bin\
36 | TRACE
37 | prompt
38 | 4
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 | Web.config
84 |
85 |
86 | Web.config
87 |
88 |
89 |
90 | 10.0
91 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 | True
101 | True
102 | 0
103 | /
104 | http://localhost:9871/
105 | False
106 | False
107 |
108 |
109 | False
110 |
111 |
112 |
113 |
114 |
121 |
--------------------------------------------------------------------------------
/ModularDemo/Scripts2/require.js:
--------------------------------------------------------------------------------
1 | /** vim: et:ts=4:sw=4:sts=4
2 | * @license RequireJS 2.0.4 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
3 | * Available via the MIT or new BSD license.
4 | * see: http://github.com/jrburke/requirejs for details
5 | */
6 | /*jslint regexp: true, nomen: true */
7 | /*global window, navigator, document, importScripts, jQuery, setTimeout, opera */
8 |
9 | var requirejs, require, define;
10 | (function (global) {
11 | 'use strict';
12 |
13 | var version = '2.0.4',
14 | commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
15 | cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
16 | jsSuffixRegExp = /\.js$/,
17 | currDirRegExp = /^\.\//,
18 | ostring = Object.prototype.toString,
19 | ap = Array.prototype,
20 | aps = ap.slice,
21 | apsp = ap.splice,
22 | isBrowser = !!(typeof window !== 'undefined' && navigator && document),
23 | isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
24 | //PS3 indicates loaded and complete, but need to wait for complete
25 | //specifically. Sequence is 'loading', 'loaded', execution,
26 | // then 'complete'. The UA check is unfortunate, but not sure how
27 | //to feature test w/o causing perf issues.
28 | readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
29 | /^complete$/ : /^(complete|loaded)$/,
30 | defContextName = '_',
31 | //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
32 | isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
33 | contexts = {},
34 | cfg = {},
35 | globalDefQueue = [],
36 | useInteractive = false,
37 | req, s, head, baseElement, dataMain, src,
38 | interactiveScript, currentlyAddingScript, mainScript, subPath;
39 |
40 | function isFunction(it) {
41 | return ostring.call(it) === '[object Function]';
42 | }
43 |
44 | function isArray(it) {
45 | return ostring.call(it) === '[object Array]';
46 | }
47 |
48 | /**
49 | * Helper function for iterating over an array. If the func returns
50 | * a true value, it will break out of the loop.
51 | */
52 | function each(ary, func) {
53 | if (ary) {
54 | var i;
55 | for (i = 0; i < ary.length; i += 1) {
56 | if (ary[i] && func(ary[i], i, ary)) {
57 | break;
58 | }
59 | }
60 | }
61 | }
62 |
63 | /**
64 | * Helper function for iterating over an array backwards. If the func
65 | * returns a true value, it will break out of the loop.
66 | */
67 | function eachReverse(ary, func) {
68 | if (ary) {
69 | var i;
70 | for (i = ary.length - 1; i > -1; i -= 1) {
71 | if (ary[i] && func(ary[i], i, ary)) {
72 | break;
73 | }
74 | }
75 | }
76 | }
77 |
78 | function hasProp(obj, prop) {
79 | return obj.hasOwnProperty(prop);
80 | }
81 |
82 | /**
83 | * Cycles over properties in an object and calls a function for each
84 | * property value. If the function returns a truthy value, then the
85 | * iteration is stopped.
86 | */
87 | function eachProp(obj, func) {
88 | var prop;
89 | for (prop in obj) {
90 | if (obj.hasOwnProperty(prop)) {
91 | if (func(obj[prop], prop)) {
92 | break;
93 | }
94 | }
95 | }
96 | }
97 |
98 | /**
99 | * Simple function to mix in properties from source into target,
100 | * but only if target does not already have a property of the same name.
101 | * This is not robust in IE for transferring methods that match
102 | * Object.prototype names, but the uses of mixin here seem unlikely to
103 | * trigger a problem related to that.
104 | */
105 | function mixin(target, source, force, deepStringMixin) {
106 | if (source) {
107 | eachProp(source, function (value, prop) {
108 | if (force || !hasProp(target, prop)) {
109 | if (deepStringMixin && typeof value !== 'string') {
110 | if (!target[prop]) {
111 | target[prop] = {};
112 | }
113 | mixin(target[prop], value, force, deepStringMixin);
114 | } else {
115 | target[prop] = value;
116 | }
117 | }
118 | });
119 | }
120 | return target;
121 | }
122 |
123 | //Similar to Function.prototype.bind, but the 'this' object is specified
124 | //first, since it is easier to read/figure out what 'this' will be.
125 | function bind(obj, fn) {
126 | return function () {
127 | return fn.apply(obj, arguments);
128 | };
129 | }
130 |
131 | function scripts() {
132 | return document.getElementsByTagName('script');
133 | }
134 |
135 | //Allow getting a global that expressed in
136 | //dot notation, like 'a.b.c'.
137 | function getGlobal(value) {
138 | if (!value) {
139 | return value;
140 | }
141 | var g = global;
142 | each(value.split('.'), function (part) {
143 | g = g[part];
144 | });
145 | return g;
146 | }
147 |
148 | function makeContextModuleFunc(func, relMap, enableBuildCallback) {
149 | return function () {
150 | //A version of a require function that passes a moduleName
151 | //value for items that may need to
152 | //look up paths relative to the moduleName
153 | var args = aps.call(arguments, 0), lastArg;
154 | if (enableBuildCallback &&
155 | isFunction((lastArg = args[args.length - 1]))) {
156 | lastArg.__requireJsBuild = true;
157 | }
158 | args.push(relMap);
159 | return func.apply(null, args);
160 | };
161 | }
162 |
163 | function addRequireMethods(req, context, relMap) {
164 | each([
165 | ['toUrl'],
166 | ['undef'],
167 | ['defined', 'requireDefined'],
168 | ['specified', 'requireSpecified']
169 | ], function (item) {
170 | var prop = item[1] || item[0];
171 | req[item[0]] = context ? makeContextModuleFunc(context[prop], relMap) :
172 | //If no context, then use default context. Reference from
173 | //contexts instead of early binding to default context, so
174 | //that during builds, the latest instance of the default
175 | //context with its config gets used.
176 | function () {
177 | var ctx = contexts[defContextName];
178 | return ctx[prop].apply(ctx, arguments);
179 | };
180 | });
181 | }
182 |
183 | /**
184 | * Constructs an error with a pointer to an URL with more information.
185 | * @param {String} id the error ID that maps to an ID on a web page.
186 | * @param {String} message human readable error.
187 | * @param {Error} [err] the original error, if there is one.
188 | *
189 | * @returns {Error}
190 | */
191 | function makeError(id, msg, err, requireModules) {
192 | var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
193 | e.requireType = id;
194 | e.requireModules = requireModules;
195 | if (err) {
196 | e.originalError = err;
197 | }
198 | return e;
199 | }
200 |
201 | if (typeof define !== 'undefined') {
202 | //If a define is already in play via another AMD loader,
203 | //do not overwrite.
204 | return;
205 | }
206 |
207 | if (typeof requirejs !== 'undefined') {
208 | if (isFunction(requirejs)) {
209 | //Do not overwrite and existing requirejs instance.
210 | return;
211 | }
212 | cfg = requirejs;
213 | requirejs = undefined;
214 | }
215 |
216 | //Allow for a require config object
217 | if (typeof require !== 'undefined' && !isFunction(require)) {
218 | //assume it is a config object.
219 | cfg = require;
220 | require = undefined;
221 | }
222 |
223 | function newContext(contextName) {
224 | var config = {
225 | waitSeconds: 7,
226 | baseUrl: './',
227 | paths: {},
228 | pkgs: {},
229 | shim: {}
230 | },
231 | registry = {},
232 | undefEvents = {},
233 | defQueue = [],
234 | defined = {},
235 | urlFetched = {},
236 | requireCounter = 1,
237 | unnormalizedCounter = 1,
238 | //Used to track the order in which modules
239 | //should be executed, by the order they
240 | //load. Important for consistent cycle resolution
241 | //behavior.
242 | waitAry = [],
243 | inCheckLoaded, Module, context, handlers,
244 | checkLoadedTimeoutId;
245 |
246 | /**
247 | * Trims the . and .. from an array of path segments.
248 | * It will keep a leading path segment if a .. will become
249 | * the first path segment, to help with module name lookups,
250 | * which act like paths, but can be remapped. But the end result,
251 | * all paths that use this function should look normalized.
252 | * NOTE: this method MODIFIES the input array.
253 | * @param {Array} ary the array of path segments.
254 | */
255 | function trimDots(ary) {
256 | var i, part;
257 | for (i = 0; ary[i]; i+= 1) {
258 | part = ary[i];
259 | if (part === '.') {
260 | ary.splice(i, 1);
261 | i -= 1;
262 | } else if (part === '..') {
263 | if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
264 | //End of the line. Keep at least one non-dot
265 | //path segment at the front so it can be mapped
266 | //correctly to disk. Otherwise, there is likely
267 | //no path mapping for a path starting with '..'.
268 | //This can still fail, but catches the most reasonable
269 | //uses of ..
270 | break;
271 | } else if (i > 0) {
272 | ary.splice(i - 1, 2);
273 | i -= 2;
274 | }
275 | }
276 | }
277 | }
278 |
279 | /**
280 | * Given a relative module name, like ./something, normalize it to
281 | * a real name that can be mapped to a path.
282 | * @param {String} name the relative name
283 | * @param {String} baseName a real name that the name arg is relative
284 | * to.
285 | * @param {Boolean} applyMap apply the map config to the value. Should
286 | * only be done if this normalization is for a dependency ID.
287 | * @returns {String} normalized name
288 | */
289 | function normalize(name, baseName, applyMap) {
290 | var baseParts = baseName && baseName.split('/'),
291 | normalizedBaseParts = baseParts,
292 | map = config.map,
293 | starMap = map && map['*'],
294 | pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
295 | foundMap;
296 |
297 | //Adjust any relative paths.
298 | if (name && name.charAt(0) === '.') {
299 | //If have a base name, try to normalize against it,
300 | //otherwise, assume it is a top-level require that will
301 | //be relative to baseUrl in the end.
302 | if (baseName) {
303 | if (config.pkgs[baseName]) {
304 | //If the baseName is a package name, then just treat it as one
305 | //name to concat the name with.
306 | normalizedBaseParts = baseParts = [baseName];
307 | } else {
308 | //Convert baseName to array, and lop off the last part,
309 | //so that . matches that 'directory' and not name of the baseName's
310 | //module. For instance, baseName of 'one/two/three', maps to
311 | //'one/two/three.js', but we want the directory, 'one/two' for
312 | //this normalization.
313 | normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
314 | }
315 |
316 | name = normalizedBaseParts.concat(name.split('/'));
317 | trimDots(name);
318 |
319 | //Some use of packages may use a . path to reference the
320 | //'main' module name, so normalize for that.
321 | pkgConfig = config.pkgs[(pkgName = name[0])];
322 | name = name.join('/');
323 | if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
324 | name = pkgName;
325 | }
326 | } else if (name.indexOf('./') === 0) {
327 | // No baseName, so this is ID is resolved relative
328 | // to baseUrl, pull off the leading dot.
329 | name = name.substring(2);
330 | }
331 | }
332 |
333 | //Apply map config if available.
334 | if (applyMap && (baseParts || starMap) && map) {
335 | nameParts = name.split('/');
336 |
337 | for (i = nameParts.length; i > 0; i -= 1) {
338 | nameSegment = nameParts.slice(0, i).join('/');
339 |
340 | if (baseParts) {
341 | //Find the longest baseName segment match in the config.
342 | //So, do joins on the biggest to smallest lengths of baseParts.
343 | for (j = baseParts.length; j > 0; j -= 1) {
344 | mapValue = map[baseParts.slice(0, j).join('/')];
345 |
346 | //baseName segment has config, find if it has one for
347 | //this name.
348 | if (mapValue) {
349 | mapValue = mapValue[nameSegment];
350 | if (mapValue) {
351 | //Match, update name to the new value.
352 | foundMap = mapValue;
353 | break;
354 | }
355 | }
356 | }
357 | }
358 |
359 | if (!foundMap && starMap && starMap[nameSegment]) {
360 | foundMap = starMap[nameSegment];
361 | }
362 |
363 | if (foundMap) {
364 | nameParts.splice(0, i, foundMap);
365 | name = nameParts.join('/');
366 | break;
367 | }
368 | }
369 | }
370 |
371 | return name;
372 | }
373 |
374 | function removeScript(name) {
375 | if (isBrowser) {
376 | each(scripts(), function (scriptNode) {
377 | if (scriptNode.getAttribute('data-requiremodule') === name &&
378 | scriptNode.getAttribute('data-requirecontext') === context.contextName) {
379 | scriptNode.parentNode.removeChild(scriptNode);
380 | return true;
381 | }
382 | });
383 | }
384 | }
385 |
386 | function hasPathFallback(id) {
387 | var pathConfig = config.paths[id];
388 | if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
389 | removeScript(id);
390 | //Pop off the first array value, since it failed, and
391 | //retry
392 | pathConfig.shift();
393 | context.undef(id);
394 | context.require([id]);
395 | return true;
396 | }
397 | }
398 |
399 | /**
400 | * Creates a module mapping that includes plugin prefix, module
401 | * name, and path. If parentModuleMap is provided it will
402 | * also normalize the name via require.normalize()
403 | *
404 | * @param {String} name the module name
405 | * @param {String} [parentModuleMap] parent module map
406 | * for the module name, used to resolve relative names.
407 | * @param {Boolean} isNormalized: is the ID already normalized.
408 | * This is true if this call is done for a define() module ID.
409 | * @param {Boolean} applyMap: apply the map config to the ID.
410 | * Should only be true if this map is for a dependency.
411 | *
412 | * @returns {Object}
413 | */
414 | function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
415 | var index = name ? name.indexOf('!') : -1,
416 | prefix = null,
417 | parentName = parentModuleMap ? parentModuleMap.name : null,
418 | originalName = name,
419 | isDefine = true,
420 | normalizedName = '',
421 | url, pluginModule, suffix;
422 |
423 | //If no name, then it means it is a require call, generate an
424 | //internal name.
425 | if (!name) {
426 | isDefine = false;
427 | name = '_@r' + (requireCounter += 1);
428 | }
429 |
430 | if (index !== -1) {
431 | prefix = name.substring(0, index);
432 | name = name.substring(index + 1, name.length);
433 | }
434 |
435 | if (prefix) {
436 | prefix = normalize(prefix, parentName, applyMap);
437 | pluginModule = defined[prefix];
438 | }
439 |
440 | //Account for relative paths if there is a base name.
441 | if (name) {
442 | if (prefix) {
443 | if (pluginModule && pluginModule.normalize) {
444 | //Plugin is loaded, use its normalize method.
445 | normalizedName = pluginModule.normalize(name, function (name) {
446 | return normalize(name, parentName, applyMap);
447 | });
448 | } else {
449 | normalizedName = normalize(name, parentName, applyMap);
450 | }
451 | } else {
452 | //A regular module.
453 | normalizedName = normalize(name, parentName, applyMap);
454 | url = context.nameToUrl(normalizedName);
455 | }
456 | }
457 |
458 | //If the id is a plugin id that cannot be determined if it needs
459 | //normalization, stamp it with a unique ID so two matching relative
460 | //ids that may conflict can be separate.
461 | suffix = prefix && !pluginModule && !isNormalized ?
462 | '_unnormalized' + (unnormalizedCounter += 1) :
463 | '';
464 |
465 | return {
466 | prefix: prefix,
467 | name: normalizedName,
468 | parentMap: parentModuleMap,
469 | unnormalized: !!suffix,
470 | url: url,
471 | originalName: originalName,
472 | isDefine: isDefine,
473 | id: (prefix ?
474 | prefix + '!' + normalizedName :
475 | normalizedName) + suffix
476 | };
477 | }
478 |
479 | function getModule(depMap) {
480 | var id = depMap.id,
481 | mod = registry[id];
482 |
483 | if (!mod) {
484 | mod = registry[id] = new context.Module(depMap);
485 | }
486 |
487 | return mod;
488 | }
489 |
490 | function on(depMap, name, fn) {
491 | var id = depMap.id,
492 | mod = registry[id];
493 |
494 | if (hasProp(defined, id) &&
495 | (!mod || mod.defineEmitComplete)) {
496 | if (name === 'defined') {
497 | fn(defined[id]);
498 | }
499 | } else {
500 | getModule(depMap).on(name, fn);
501 | }
502 | }
503 |
504 | function onError(err, errback) {
505 | var ids = err.requireModules,
506 | notified = false;
507 |
508 | if (errback) {
509 | errback(err);
510 | } else {
511 | each(ids, function (id) {
512 | var mod = registry[id];
513 | if (mod) {
514 | //Set error on module, so it skips timeout checks.
515 | mod.error = err;
516 | if (mod.events.error) {
517 | notified = true;
518 | mod.emit('error', err);
519 | }
520 | }
521 | });
522 |
523 | if (!notified) {
524 | req.onError(err);
525 | }
526 | }
527 | }
528 |
529 | /**
530 | * Internal method to transfer globalQueue items to this context's
531 | * defQueue.
532 | */
533 | function takeGlobalQueue() {
534 | //Push all the globalDefQueue items into the context's defQueue
535 | if (globalDefQueue.length) {
536 | //Array splice in the values since the context code has a
537 | //local var ref to defQueue, so cannot just reassign the one
538 | //on context.
539 | apsp.apply(defQueue,
540 | [defQueue.length - 1, 0].concat(globalDefQueue));
541 | globalDefQueue = [];
542 | }
543 | }
544 |
545 | /**
546 | * Helper function that creates a require function object to give to
547 | * modules that ask for it as a dependency. It needs to be specific
548 | * per module because of the implication of path mappings that may
549 | * need to be relative to the module name.
550 | */
551 | function makeRequire(mod, enableBuildCallback, altRequire) {
552 | var relMap = mod && mod.map,
553 | modRequire = makeContextModuleFunc(altRequire || context.require,
554 | relMap,
555 | enableBuildCallback);
556 |
557 | addRequireMethods(modRequire, context, relMap);
558 | modRequire.isBrowser = isBrowser;
559 |
560 | return modRequire;
561 | }
562 |
563 | handlers = {
564 | 'require': function (mod) {
565 | return makeRequire(mod);
566 | },
567 | 'exports': function (mod) {
568 | mod.usingExports = true;
569 | if (mod.map.isDefine) {
570 | return (mod.exports = defined[mod.map.id] = {});
571 | }
572 | },
573 | 'module': function (mod) {
574 | return (mod.module = {
575 | id: mod.map.id,
576 | uri: mod.map.url,
577 | config: function () {
578 | return (config.config && config.config[mod.map.id]) || {};
579 | },
580 | exports: defined[mod.map.id]
581 | });
582 | }
583 | };
584 |
585 | function removeWaiting(id) {
586 | //Clean up machinery used for waiting modules.
587 | delete registry[id];
588 |
589 | each(waitAry, function (mod, i) {
590 | if (mod.map.id === id) {
591 | waitAry.splice(i, 1);
592 | if (!mod.defined) {
593 | context.waitCount -= 1;
594 | }
595 | return true;
596 | }
597 | });
598 | }
599 |
600 | function findCycle(mod, traced) {
601 | var id = mod.map.id,
602 | depArray = mod.depMaps,
603 | foundModule;
604 |
605 | //Do not bother with unitialized modules or not yet enabled
606 | //modules.
607 | if (!mod.inited) {
608 | return;
609 | }
610 |
611 | //Found the cycle.
612 | if (traced[id]) {
613 | return mod;
614 | }
615 |
616 | traced[id] = true;
617 |
618 | //Trace through the dependencies.
619 | each(depArray, function (depMap) {
620 | var depId = depMap.id,
621 | depMod = registry[depId];
622 |
623 | if (!depMod) {
624 | return;
625 | }
626 |
627 | if (!depMod.inited || !depMod.enabled) {
628 | //Dependency is not inited, so this cannot
629 | //be used to determine a cycle.
630 | foundModule = null;
631 | delete traced[id];
632 | return true;
633 | }
634 |
635 | //mixin traced to a new object for each dependency, so that
636 | //sibling dependencies in this object to not generate a
637 | //false positive match on a cycle. Ideally an Object.create
638 | //type of prototype delegation would be used here, but
639 | //optimizing for file size vs. execution speed since hopefully
640 | //the trees are small for circular dependency scans relative
641 | //to the full app perf.
642 | return (foundModule = findCycle(depMod, mixin({}, traced)));
643 | });
644 |
645 | return foundModule;
646 | }
647 |
648 | function forceExec(mod, traced, uninited) {
649 | var id = mod.map.id,
650 | depArray = mod.depMaps;
651 |
652 | if (!mod.inited || !mod.map.isDefine) {
653 | return;
654 | }
655 |
656 | if (traced[id]) {
657 | return defined[id];
658 | }
659 |
660 | traced[id] = mod;
661 |
662 | each(depArray, function(depMap) {
663 | var depId = depMap.id,
664 | depMod = registry[depId],
665 | value;
666 |
667 | if (handlers[depId]) {
668 | return;
669 | }
670 |
671 | if (depMod) {
672 | if (!depMod.inited || !depMod.enabled) {
673 | //Dependency is not inited,
674 | //so this module cannot be
675 | //given a forced value yet.
676 | uninited[id] = true;
677 | return;
678 | }
679 |
680 | //Get the value for the current dependency
681 | value = forceExec(depMod, traced, uninited);
682 |
683 | //Even with forcing it may not be done,
684 | //in particular if the module is waiting
685 | //on a plugin resource.
686 | if (!uninited[depId]) {
687 | mod.defineDepById(depId, value);
688 | }
689 | }
690 | });
691 |
692 | mod.check(true);
693 |
694 | return defined[id];
695 | }
696 |
697 | function modCheck(mod) {
698 | mod.check();
699 | }
700 |
701 | function checkLoaded() {
702 | var waitInterval = config.waitSeconds * 1000,
703 | //It is possible to disable the wait interval by using waitSeconds of 0.
704 | expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
705 | noLoads = [],
706 | stillLoading = false,
707 | needCycleCheck = true,
708 | map, modId, err, usingPathFallback;
709 |
710 | //Do not bother if this call was a result of a cycle break.
711 | if (inCheckLoaded) {
712 | return;
713 | }
714 |
715 | inCheckLoaded = true;
716 |
717 | //Figure out the state of all the modules.
718 | eachProp(registry, function (mod) {
719 | map = mod.map;
720 | modId = map.id;
721 |
722 | //Skip things that are not enabled or in error state.
723 | if (!mod.enabled) {
724 | return;
725 | }
726 |
727 | if (!mod.error) {
728 | //If the module should be executed, and it has not
729 | //been inited and time is up, remember it.
730 | if (!mod.inited && expired) {
731 | if (hasPathFallback(modId)) {
732 | usingPathFallback = true;
733 | stillLoading = true;
734 | } else {
735 | noLoads.push(modId);
736 | removeScript(modId);
737 | }
738 | } else if (!mod.inited && mod.fetched && map.isDefine) {
739 | stillLoading = true;
740 | if (!map.prefix) {
741 | //No reason to keep looking for unfinished
742 | //loading. If the only stillLoading is a
743 | //plugin resource though, keep going,
744 | //because it may be that a plugin resource
745 | //is waiting on a non-plugin cycle.
746 | return (needCycleCheck = false);
747 | }
748 | }
749 | }
750 | });
751 |
752 | if (expired && noLoads.length) {
753 | //If wait time expired, throw error of unloaded modules.
754 | err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
755 | err.contextName = context.contextName;
756 | return onError(err);
757 | }
758 |
759 | //Not expired, check for a cycle.
760 | if (needCycleCheck) {
761 |
762 | each(waitAry, function (mod) {
763 | if (mod.defined) {
764 | return;
765 | }
766 |
767 | var cycleMod = findCycle(mod, {}),
768 | traced = {};
769 |
770 | if (cycleMod) {
771 | forceExec(cycleMod, traced, {});
772 |
773 | //traced modules may have been
774 | //removed from the registry, but
775 | //their listeners still need to
776 | //be called.
777 | eachProp(traced, modCheck);
778 | }
779 | });
780 |
781 | //Now that dependencies have
782 | //been satisfied, trigger the
783 | //completion check that then
784 | //notifies listeners.
785 | eachProp(registry, modCheck);
786 | }
787 |
788 | //If still waiting on loads, and the waiting load is something
789 | //other than a plugin resource, or there are still outstanding
790 | //scripts, then just try back later.
791 | if ((!expired || usingPathFallback) && stillLoading) {
792 | //Something is still waiting to load. Wait for it, but only
793 | //if a timeout is not already in effect.
794 | if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
795 | checkLoadedTimeoutId = setTimeout(function () {
796 | checkLoadedTimeoutId = 0;
797 | checkLoaded();
798 | }, 50);
799 | }
800 | }
801 |
802 | inCheckLoaded = false;
803 | }
804 |
805 | Module = function (map) {
806 | this.events = undefEvents[map.id] || {};
807 | this.map = map;
808 | this.shim = config.shim[map.id];
809 | this.depExports = [];
810 | this.depMaps = [];
811 | this.depMatched = [];
812 | this.pluginMaps = {};
813 | this.depCount = 0;
814 |
815 | /* this.exports this.factory
816 | this.depMaps = [],
817 | this.enabled, this.fetched
818 | */
819 | };
820 |
821 | Module.prototype = {
822 | init: function(depMaps, factory, errback, options) {
823 | options = options || {};
824 |
825 | //Do not do more inits if already done. Can happen if there
826 | //are multiple define calls for the same module. That is not
827 | //a normal, common case, but it is also not unexpected.
828 | if (this.inited) {
829 | return;
830 | }
831 |
832 | this.factory = factory;
833 |
834 | if (errback) {
835 | //Register for errors on this module.
836 | this.on('error', errback);
837 | } else if (this.events.error) {
838 | //If no errback already, but there are error listeners
839 | //on this module, set up an errback to pass to the deps.
840 | errback = bind(this, function (err) {
841 | this.emit('error', err);
842 | });
843 | }
844 |
845 | //Do a copy of the dependency array, so that
846 | //source inputs are not modified. For example
847 | //"shim" deps are passed in here directly, and
848 | //doing a direct modification of the depMaps array
849 | //would affect that config.
850 | this.depMaps = depMaps && depMaps.slice(0);
851 | this.depMaps.rjsSkipMap = depMaps.rjsSkipMap;
852 |
853 | this.errback = errback;
854 |
855 | //Indicate this module has be initialized
856 | this.inited = true;
857 |
858 | this.ignore = options.ignore;
859 |
860 | //Could have option to init this module in enabled mode,
861 | //or could have been previously marked as enabled. However,
862 | //the dependencies are not known until init is called. So
863 | //if enabled previously, now trigger dependencies as enabled.
864 | if (options.enabled || this.enabled) {
865 | //Enable this module and dependencies.
866 | //Will call this.check()
867 | this.enable();
868 | } else {
869 | this.check();
870 | }
871 | },
872 |
873 | defineDepById: function (id, depExports) {
874 | var i;
875 |
876 | //Find the index for this dependency.
877 | each(this.depMaps, function (map, index) {
878 | if (map.id === id) {
879 | i = index;
880 | return true;
881 | }
882 | });
883 |
884 | return this.defineDep(i, depExports);
885 | },
886 |
887 | defineDep: function (i, depExports) {
888 | //Because of cycles, defined callback for a given
889 | //export can be called more than once.
890 | if (!this.depMatched[i]) {
891 | this.depMatched[i] = true;
892 | this.depCount -= 1;
893 | this.depExports[i] = depExports;
894 | }
895 | },
896 |
897 | fetch: function () {
898 | if (this.fetched) {
899 | return;
900 | }
901 | this.fetched = true;
902 |
903 | context.startTime = (new Date()).getTime();
904 |
905 | var map = this.map;
906 |
907 | //If the manager is for a plugin managed resource,
908 | //ask the plugin to load it now.
909 | if (this.shim) {
910 | makeRequire(this, true)(this.shim.deps || [], bind(this, function () {
911 | return map.prefix ? this.callPlugin() : this.load();
912 | }));
913 | } else {
914 | //Regular dependency.
915 | return map.prefix ? this.callPlugin() : this.load();
916 | }
917 | },
918 |
919 | load: function() {
920 | var url = this.map.url;
921 |
922 | //Regular dependency.
923 | if (!urlFetched[url]) {
924 | urlFetched[url] = true;
925 | context.load(this.map.id, url);
926 | }
927 | },
928 |
929 | /**
930 | * Checks is the module is ready to define itself, and if so,
931 | * define it. If the silent argument is true, then it will just
932 | * define, but not notify listeners, and not ask for a context-wide
933 | * check of all loaded modules. That is useful for cycle breaking.
934 | */
935 | check: function (silent) {
936 | if (!this.enabled || this.enabling) {
937 | return;
938 | }
939 |
940 | var id = this.map.id,
941 | depExports = this.depExports,
942 | exports = this.exports,
943 | factory = this.factory,
944 | err, cjsModule;
945 |
946 | if (!this.inited) {
947 | this.fetch();
948 | } else if (this.error) {
949 | this.emit('error', this.error);
950 | } else if (!this.defining) {
951 | //The factory could trigger another require call
952 | //that would result in checking this module to
953 | //define itself again. If already in the process
954 | //of doing that, skip this work.
955 | this.defining = true;
956 |
957 | if (this.depCount < 1 && !this.defined) {
958 | if (isFunction(factory)) {
959 | //If there is an error listener, favor passing
960 | //to that instead of throwing an error.
961 | if (this.events.error) {
962 | try {
963 | exports = context.execCb(id, factory, depExports, exports);
964 | } catch (e) {
965 | err = e;
966 | }
967 | } else {
968 | exports = context.execCb(id, factory, depExports, exports);
969 | }
970 |
971 | if (this.map.isDefine) {
972 | //If setting exports via 'module' is in play,
973 | //favor that over return value and exports. After that,
974 | //favor a non-undefined return value over exports use.
975 | cjsModule = this.module;
976 | if (cjsModule &&
977 | cjsModule.exports !== undefined &&
978 | //Make sure it is not already the exports value
979 | cjsModule.exports !== this.exports) {
980 | exports = cjsModule.exports;
981 | } else if (exports === undefined && this.usingExports) {
982 | //exports already set the defined value.
983 | exports = this.exports;
984 | }
985 | }
986 |
987 | if (err) {
988 | err.requireMap = this.map;
989 | err.requireModules = [this.map.id];
990 | err.requireType = 'define';
991 | return onError((this.error = err));
992 | }
993 |
994 | } else {
995 | //Just a literal value
996 | exports = factory;
997 | }
998 |
999 | this.exports = exports;
1000 |
1001 | if (this.map.isDefine && !this.ignore) {
1002 | defined[id] = exports;
1003 |
1004 | if (req.onResourceLoad) {
1005 | req.onResourceLoad(context, this.map, this.depMaps);
1006 | }
1007 | }
1008 |
1009 | //Clean up
1010 | delete registry[id];
1011 |
1012 | this.defined = true;
1013 | context.waitCount -= 1;
1014 | if (context.waitCount === 0) {
1015 | //Clear the wait array used for cycles.
1016 | waitAry = [];
1017 | }
1018 | }
1019 |
1020 | //Finished the define stage. Allow calling check again
1021 | //to allow define notifications below in the case of a
1022 | //cycle.
1023 | this.defining = false;
1024 |
1025 | if (!silent) {
1026 | if (this.defined && !this.defineEmitted) {
1027 | this.defineEmitted = true;
1028 | this.emit('defined', this.exports);
1029 | this.defineEmitComplete = true;
1030 | }
1031 | }
1032 | }
1033 | },
1034 |
1035 | callPlugin: function() {
1036 | var map = this.map,
1037 | id = map.id,
1038 | pluginMap = makeModuleMap(map.prefix, null, false, true);
1039 |
1040 | on(pluginMap, 'defined', bind(this, function (plugin) {
1041 | var name = this.map.name,
1042 | parentName = this.map.parentMap ? this.map.parentMap.name : null,
1043 | load, normalizedMap, normalizedMod;
1044 |
1045 | //If current map is not normalized, wait for that
1046 | //normalized name to load instead of continuing.
1047 | if (this.map.unnormalized) {
1048 | //Normalize the ID if the plugin allows it.
1049 | if (plugin.normalize) {
1050 | name = plugin.normalize(name, function (name) {
1051 | return normalize(name, parentName, true);
1052 | }) || '';
1053 | }
1054 |
1055 | normalizedMap = makeModuleMap(map.prefix + '!' + name,
1056 | this.map.parentMap,
1057 | false,
1058 | true);
1059 | on(normalizedMap,
1060 | 'defined', bind(this, function (value) {
1061 | this.init([], function () { return value; }, null, {
1062 | enabled: true,
1063 | ignore: true
1064 | });
1065 | }));
1066 | normalizedMod = registry[normalizedMap.id];
1067 | if (normalizedMod) {
1068 | if (this.events.error) {
1069 | normalizedMod.on('error', bind(this, function (err) {
1070 | this.emit('error', err);
1071 | }));
1072 | }
1073 | normalizedMod.enable();
1074 | }
1075 |
1076 | return;
1077 | }
1078 |
1079 | load = bind(this, function (value) {
1080 | this.init([], function () { return value; }, null, {
1081 | enabled: true
1082 | });
1083 | });
1084 |
1085 | load.error = bind(this, function (err) {
1086 | this.inited = true;
1087 | this.error = err;
1088 | err.requireModules = [id];
1089 |
1090 | //Remove temp unnormalized modules for this module,
1091 | //since they will never be resolved otherwise now.
1092 | eachProp(registry, function (mod) {
1093 | if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
1094 | removeWaiting(mod.map.id);
1095 | }
1096 | });
1097 |
1098 | onError(err);
1099 | });
1100 |
1101 | //Allow plugins to load other code without having to know the
1102 | //context or how to 'complete' the load.
1103 | load.fromText = function (moduleName, text) {
1104 | /*jslint evil: true */
1105 | var hasInteractive = useInteractive;
1106 |
1107 | //Turn off interactive script matching for IE for any define
1108 | //calls in the text, then turn it back on at the end.
1109 | if (hasInteractive) {
1110 | useInteractive = false;
1111 | }
1112 |
1113 | //Prime the system by creating a module instance for
1114 | //it.
1115 | getModule(makeModuleMap(moduleName));
1116 |
1117 | req.exec(text);
1118 |
1119 | if (hasInteractive) {
1120 | useInteractive = true;
1121 | }
1122 |
1123 | //Support anonymous modules.
1124 | context.completeLoad(moduleName);
1125 | };
1126 |
1127 | //Use parentName here since the plugin's name is not reliable,
1128 | //could be some weird string with no path that actually wants to
1129 | //reference the parentName's path.
1130 | plugin.load(map.name, makeRequire(map.parentMap, true, function (deps, cb) {
1131 | deps.rjsSkipMap = true;
1132 | return context.require(deps, cb);
1133 | }), load, config);
1134 | }));
1135 |
1136 | context.enable(pluginMap, this);
1137 | this.pluginMaps[pluginMap.id] = pluginMap;
1138 | },
1139 |
1140 | enable: function () {
1141 | this.enabled = true;
1142 |
1143 | if (!this.waitPushed) {
1144 | waitAry.push(this);
1145 | context.waitCount += 1;
1146 | this.waitPushed = true;
1147 | }
1148 |
1149 | //Set flag mentioning that the module is enabling,
1150 | //so that immediate calls to the defined callbacks
1151 | //for dependencies do not trigger inadvertent load
1152 | //with the depCount still being zero.
1153 | this.enabling = true;
1154 |
1155 | //Enable each dependency
1156 | each(this.depMaps, bind(this, function (depMap, i) {
1157 | var id, mod, handler;
1158 |
1159 | if (typeof depMap === 'string') {
1160 | //Dependency needs to be converted to a depMap
1161 | //and wired up to this module.
1162 | depMap = makeModuleMap(depMap,
1163 | (this.map.isDefine ? this.map : this.map.parentMap),
1164 | false,
1165 | !this.depMaps.rjsSkipMap);
1166 | this.depMaps[i] = depMap;
1167 |
1168 | handler = handlers[depMap.id];
1169 |
1170 | if (handler) {
1171 | this.depExports[i] = handler(this);
1172 | return;
1173 | }
1174 |
1175 | this.depCount += 1;
1176 |
1177 | on(depMap, 'defined', bind(this, function (depExports) {
1178 | this.defineDep(i, depExports);
1179 | this.check();
1180 | }));
1181 |
1182 | if (this.errback) {
1183 | on(depMap, 'error', this.errback);
1184 | }
1185 | }
1186 |
1187 | id = depMap.id;
1188 | mod = registry[id];
1189 |
1190 | //Skip special modules like 'require', 'exports', 'module'
1191 | //Also, don't call enable if it is already enabled,
1192 | //important in circular dependency cases.
1193 | if (!handlers[id] && mod && !mod.enabled) {
1194 | context.enable(depMap, this);
1195 | }
1196 | }));
1197 |
1198 | //Enable each plugin that is used in
1199 | //a dependency
1200 | eachProp(this.pluginMaps, bind(this, function (pluginMap) {
1201 | var mod = registry[pluginMap.id];
1202 | if (mod && !mod.enabled) {
1203 | context.enable(pluginMap, this);
1204 | }
1205 | }));
1206 |
1207 | this.enabling = false;
1208 |
1209 | this.check();
1210 | },
1211 |
1212 | on: function(name, cb) {
1213 | var cbs = this.events[name];
1214 | if (!cbs) {
1215 | cbs = this.events[name] = [];
1216 | }
1217 | cbs.push(cb);
1218 | },
1219 |
1220 | emit: function (name, evt) {
1221 | each(this.events[name], function (cb) {
1222 | cb(evt);
1223 | });
1224 | if (name === 'error') {
1225 | //Now that the error handler was triggered, remove
1226 | //the listeners, since this broken Module instance
1227 | //can stay around for a while in the registry/waitAry.
1228 | delete this.events[name];
1229 | }
1230 | }
1231 | };
1232 |
1233 | function callGetModule(args) {
1234 | getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
1235 | }
1236 |
1237 | function removeListener(node, func, name, ieName) {
1238 | //Favor detachEvent because of IE9
1239 | //issue, see attachEvent/addEventListener comment elsewhere
1240 | //in this file.
1241 | if (node.detachEvent && !isOpera) {
1242 | //Probably IE. If not it will throw an error, which will be
1243 | //useful to know.
1244 | if (ieName) {
1245 | node.detachEvent(ieName, func);
1246 | }
1247 | } else {
1248 | node.removeEventListener(name, func, false);
1249 | }
1250 | }
1251 |
1252 | /**
1253 | * Given an event from a script node, get the requirejs info from it,
1254 | * and then removes the event listeners on the node.
1255 | * @param {Event} evt
1256 | * @returns {Object}
1257 | */
1258 | function getScriptData(evt) {
1259 | //Using currentTarget instead of target for Firefox 2.0's sake. Not
1260 | //all old browsers will be supported, but this one was easy enough
1261 | //to support and still makes sense.
1262 | var node = evt.currentTarget || evt.srcElement;
1263 |
1264 | //Remove the listeners once here.
1265 | removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
1266 | removeListener(node, context.onScriptError, 'error');
1267 |
1268 | return {
1269 | node: node,
1270 | id: node && node.getAttribute('data-requiremodule')
1271 | };
1272 | }
1273 |
1274 | return (context = {
1275 | config: config,
1276 | contextName: contextName,
1277 | registry: registry,
1278 | defined: defined,
1279 | urlFetched: urlFetched,
1280 | waitCount: 0,
1281 | defQueue: defQueue,
1282 | Module: Module,
1283 | makeModuleMap: makeModuleMap,
1284 |
1285 | /**
1286 | * Set a configuration for the context.
1287 | * @param {Object} cfg config object to integrate.
1288 | */
1289 | configure: function (cfg) {
1290 | //Make sure the baseUrl ends in a slash.
1291 | if (cfg.baseUrl) {
1292 | if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
1293 | cfg.baseUrl += '/';
1294 | }
1295 | }
1296 |
1297 | //Save off the paths and packages since they require special processing,
1298 | //they are additive.
1299 | var pkgs = config.pkgs,
1300 | shim = config.shim,
1301 | paths = config.paths,
1302 | map = config.map;
1303 |
1304 | //Mix in the config values, favoring the new values over
1305 | //existing ones in context.config.
1306 | mixin(config, cfg, true);
1307 |
1308 | //Merge paths.
1309 | config.paths = mixin(paths, cfg.paths, true);
1310 |
1311 | //Merge map
1312 | if (cfg.map) {
1313 | config.map = mixin(map || {}, cfg.map, true, true);
1314 | }
1315 |
1316 | //Merge shim
1317 | if (cfg.shim) {
1318 | eachProp(cfg.shim, function (value, id) {
1319 | //Normalize the structure
1320 | if (isArray(value)) {
1321 | value = {
1322 | deps: value
1323 | };
1324 | }
1325 | if (value.exports && !value.exports.__buildReady) {
1326 | value.exports = context.makeShimExports(value.exports);
1327 | }
1328 | shim[id] = value;
1329 | });
1330 | config.shim = shim;
1331 | }
1332 |
1333 | //Adjust packages if necessary.
1334 | if (cfg.packages) {
1335 | each(cfg.packages, function (pkgObj) {
1336 | var location;
1337 |
1338 | pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
1339 | location = pkgObj.location;
1340 |
1341 | //Create a brand new object on pkgs, since currentPackages can
1342 | //be passed in again, and config.pkgs is the internal transformed
1343 | //state for all package configs.
1344 | pkgs[pkgObj.name] = {
1345 | name: pkgObj.name,
1346 | location: location || pkgObj.name,
1347 | //Remove leading dot in main, so main paths are normalized,
1348 | //and remove any trailing .js, since different package
1349 | //envs have different conventions: some use a module name,
1350 | //some use a file name.
1351 | main: (pkgObj.main || 'main')
1352 | .replace(currDirRegExp, '')
1353 | .replace(jsSuffixRegExp, '')
1354 | };
1355 | });
1356 |
1357 | //Done with modifications, assing packages back to context config
1358 | config.pkgs = pkgs;
1359 | }
1360 |
1361 | //If there are any "waiting to execute" modules in the registry,
1362 | //update the maps for them, since their info, like URLs to load,
1363 | //may have changed.
1364 | eachProp(registry, function (mod, id) {
1365 | mod.map = makeModuleMap(id);
1366 | });
1367 |
1368 | //If a deps array or a config callback is specified, then call
1369 | //require with those args. This is useful when require is defined as a
1370 | //config object before require.js is loaded.
1371 | if (cfg.deps || cfg.callback) {
1372 | context.require(cfg.deps || [], cfg.callback);
1373 | }
1374 | },
1375 |
1376 | makeShimExports: function (exports) {
1377 | var func;
1378 | if (typeof exports === 'string') {
1379 | func = function () {
1380 | return getGlobal(exports);
1381 | };
1382 | //Save the exports for use in nodefine checking.
1383 | func.exports = exports;
1384 | return func;
1385 | } else {
1386 | return function () {
1387 | return exports.apply(global, arguments);
1388 | };
1389 | }
1390 | },
1391 |
1392 | requireDefined: function (id, relMap) {
1393 | return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
1394 | },
1395 |
1396 | requireSpecified: function (id, relMap) {
1397 | id = makeModuleMap(id, relMap, false, true).id;
1398 | return hasProp(defined, id) || hasProp(registry, id);
1399 | },
1400 |
1401 | require: function (deps, callback, errback, relMap) {
1402 | var moduleName, id, map, requireMod, args;
1403 | if (typeof deps === 'string') {
1404 | if (isFunction(callback)) {
1405 | //Invalid call
1406 | return onError(makeError('requireargs', 'Invalid require call'), errback);
1407 | }
1408 |
1409 | //Synchronous access to one module. If require.get is
1410 | //available (as in the Node adapter), prefer that.
1411 | //In this case deps is the moduleName and callback is
1412 | //the relMap
1413 | if (req.get) {
1414 | return req.get(context, deps, callback);
1415 | }
1416 |
1417 | //Just return the module wanted. In this scenario, the
1418 | //second arg (if passed) is just the relMap.
1419 | moduleName = deps;
1420 | relMap = callback;
1421 |
1422 | //Normalize module name, if it contains . or ..
1423 | map = makeModuleMap(moduleName, relMap, false, true);
1424 | id = map.id;
1425 |
1426 | if (!hasProp(defined, id)) {
1427 | return onError(makeError('notloaded', 'Module name "' +
1428 | id +
1429 | '" has not been loaded yet for context: ' +
1430 | contextName));
1431 | }
1432 | return defined[id];
1433 | }
1434 |
1435 | //Callback require. Normalize args. if callback or errback is
1436 | //not a function, it means it is a relMap. Test errback first.
1437 | if (errback && !isFunction(errback)) {
1438 | relMap = errback;
1439 | errback = undefined;
1440 | }
1441 | if (callback && !isFunction(callback)) {
1442 | relMap = callback;
1443 | callback = undefined;
1444 | }
1445 |
1446 | //Any defined modules in the global queue, intake them now.
1447 | takeGlobalQueue();
1448 |
1449 | //Make sure any remaining defQueue items get properly processed.
1450 | while (defQueue.length) {
1451 | args = defQueue.shift();
1452 | if (args[0] === null) {
1453 | return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
1454 | } else {
1455 | //args are id, deps, factory. Should be normalized by the
1456 | //define() function.
1457 | callGetModule(args);
1458 | }
1459 | }
1460 |
1461 | //Mark all the dependencies as needing to be loaded.
1462 | requireMod = getModule(makeModuleMap(null, relMap));
1463 |
1464 | requireMod.init(deps, callback, errback, {
1465 | enabled: true
1466 | });
1467 |
1468 | checkLoaded();
1469 |
1470 | return context.require;
1471 | },
1472 |
1473 | undef: function (id) {
1474 | var map = makeModuleMap(id, null, true),
1475 | mod = registry[id];
1476 |
1477 | delete defined[id];
1478 | delete urlFetched[map.url];
1479 | delete undefEvents[id];
1480 |
1481 | if (mod) {
1482 | //Hold on to listeners in case the
1483 | //module will be attempted to be reloaded
1484 | //using a different config.
1485 | if (mod.events.defined) {
1486 | undefEvents[id] = mod.events;
1487 | }
1488 |
1489 | removeWaiting(id);
1490 | }
1491 | },
1492 |
1493 | /**
1494 | * Called to enable a module if it is still in the registry
1495 | * awaiting enablement. parent module is passed in for context,
1496 | * used by the optimizer.
1497 | */
1498 | enable: function (depMap, parent) {
1499 | var mod = registry[depMap.id];
1500 | if (mod) {
1501 | getModule(depMap).enable();
1502 | }
1503 | },
1504 |
1505 | /**
1506 | * Internal method used by environment adapters to complete a load event.
1507 | * A load event could be a script load or just a load pass from a synchronous
1508 | * load call.
1509 | * @param {String} moduleName the name of the module to potentially complete.
1510 | */
1511 | completeLoad: function (moduleName) {
1512 | var shim = config.shim[moduleName] || {},
1513 | shExports = shim.exports && shim.exports.exports,
1514 | found, args, mod;
1515 |
1516 | takeGlobalQueue();
1517 |
1518 | while (defQueue.length) {
1519 | args = defQueue.shift();
1520 | if (args[0] === null) {
1521 | args[0] = moduleName;
1522 | //If already found an anonymous module and bound it
1523 | //to this name, then this is some other anon module
1524 | //waiting for its completeLoad to fire.
1525 | if (found) {
1526 | break;
1527 | }
1528 | found = true;
1529 | } else if (args[0] === moduleName) {
1530 | //Found matching define call for this script!
1531 | found = true;
1532 | }
1533 |
1534 | callGetModule(args);
1535 | }
1536 |
1537 | //Do this after the cycle of callGetModule in case the result
1538 | //of those calls/init calls changes the registry.
1539 | mod = registry[moduleName];
1540 |
1541 | if (!found &&
1542 | !defined[moduleName] &&
1543 | mod && !mod.inited) {
1544 | if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
1545 | if (hasPathFallback(moduleName)) {
1546 | return;
1547 | } else {
1548 | return onError(makeError('nodefine',
1549 | 'No define call for ' + moduleName,
1550 | null,
1551 | [moduleName]));
1552 | }
1553 | } else {
1554 | //A script that does not call define(), so just simulate
1555 | //the call for it.
1556 | callGetModule([moduleName, (shim.deps || []), shim.exports]);
1557 | }
1558 | }
1559 |
1560 | checkLoaded();
1561 | },
1562 |
1563 | /**
1564 | * Converts a module name + .extension into an URL path.
1565 | * *Requires* the use of a module name. It does not support using
1566 | * plain URLs like nameToUrl.
1567 | */
1568 | toUrl: function (moduleNamePlusExt, relModuleMap) {
1569 | var index = moduleNamePlusExt.lastIndexOf('.'),
1570 | ext = null;
1571 |
1572 | if (index !== -1) {
1573 | ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
1574 | moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
1575 | }
1576 |
1577 | return context.nameToUrl(normalize(moduleNamePlusExt, relModuleMap && relModuleMap.id, true),
1578 | ext);
1579 | },
1580 |
1581 | /**
1582 | * Converts a module name to a file path. Supports cases where
1583 | * moduleName may actually be just an URL.
1584 | * Note that it **does not** call normalize on the moduleName,
1585 | * it is assumed to have already been normalized. This is an
1586 | * internal API, not a public one. Use toUrl for the public API.
1587 | */
1588 | nameToUrl: function (moduleName, ext) {
1589 | var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
1590 | parentPath;
1591 |
1592 | //If a colon is in the URL, it indicates a protocol is used and it is just
1593 | //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
1594 | //or ends with .js, then assume the user meant to use an url and not a module id.
1595 | //The slash is important for protocol-less URLs as well as full paths.
1596 | if (req.jsExtRegExp.test(moduleName)) {
1597 | //Just a plain path, not module name lookup, so just return it.
1598 | //Add extension if it is included. This is a bit wonky, only non-.js things pass
1599 | //an extension, this method probably needs to be reworked.
1600 | url = moduleName + (ext || '');
1601 | } else {
1602 | //A module that needs to be converted to a path.
1603 | paths = config.paths;
1604 | pkgs = config.pkgs;
1605 |
1606 | syms = moduleName.split('/');
1607 | //For each module name segment, see if there is a path
1608 | //registered for it. Start with most specific name
1609 | //and work up from it.
1610 | for (i = syms.length; i > 0; i -= 1) {
1611 | parentModule = syms.slice(0, i).join('/');
1612 | pkg = pkgs[parentModule];
1613 | parentPath = paths[parentModule];
1614 | if (parentPath) {
1615 | //If an array, it means there are a few choices,
1616 | //Choose the one that is desired
1617 | if (isArray(parentPath)) {
1618 | parentPath = parentPath[0];
1619 | }
1620 | syms.splice(0, i, parentPath);
1621 | break;
1622 | } else if (pkg) {
1623 | //If module name is just the package name, then looking
1624 | //for the main module.
1625 | if (moduleName === pkg.name) {
1626 | pkgPath = pkg.location + '/' + pkg.main;
1627 | } else {
1628 | pkgPath = pkg.location;
1629 | }
1630 | syms.splice(0, i, pkgPath);
1631 | break;
1632 | }
1633 | }
1634 |
1635 | //Join the path parts together, then figure out if baseUrl is needed.
1636 | url = syms.join('/') + (ext || '.js');
1637 | url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
1638 | }
1639 |
1640 | return config.urlArgs ? url +
1641 | ((url.indexOf('?') === -1 ? '?' : '&') +
1642 | config.urlArgs) : url;
1643 | },
1644 |
1645 | //Delegates to req.load. Broken out as a separate function to
1646 | //allow overriding in the optimizer.
1647 | load: function (id, url) {
1648 | req.load(context, id, url);
1649 | },
1650 |
1651 | /**
1652 | * Executes a module callack function. Broken out as a separate function
1653 | * solely to allow the build system to sequence the files in the built
1654 | * layer in the right sequence.
1655 | *
1656 | * @private
1657 | */
1658 | execCb: function (name, callback, args, exports) {
1659 | return callback.apply(exports, args);
1660 | },
1661 |
1662 | /**
1663 | * callback for script loads, used to check status of loading.
1664 | *
1665 | * @param {Event} evt the event from the browser for the script
1666 | * that was loaded.
1667 | */
1668 | onScriptLoad: function (evt) {
1669 | //Using currentTarget instead of target for Firefox 2.0's sake. Not
1670 | //all old browsers will be supported, but this one was easy enough
1671 | //to support and still makes sense.
1672 | if (evt.type === 'load' ||
1673 | (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
1674 | //Reset interactive script so a script node is not held onto for
1675 | //to long.
1676 | interactiveScript = null;
1677 |
1678 | //Pull out the name of the module and the context.
1679 | var data = getScriptData(evt);
1680 | context.completeLoad(data.id);
1681 | }
1682 | },
1683 |
1684 | /**
1685 | * Callback for script errors.
1686 | */
1687 | onScriptError: function (evt) {
1688 | var data = getScriptData(evt);
1689 | if (!hasPathFallback(data.id)) {
1690 | return onError(makeError('scripterror', 'Script error', evt, [data.id]));
1691 | }
1692 | }
1693 | });
1694 | }
1695 |
1696 | /**
1697 | * Main entry point.
1698 | *
1699 | * If the only argument to require is a string, then the module that
1700 | * is represented by that string is fetched for the appropriate context.
1701 | *
1702 | * If the first argument is an array, then it will be treated as an array
1703 | * of dependency string names to fetch. An optional function callback can
1704 | * be specified to execute when all of those dependencies are available.
1705 | *
1706 | * Make a local req variable to help Caja compliance (it assumes things
1707 | * on a require that are not standardized), and to give a short
1708 | * name for minification/local scope use.
1709 | */
1710 | req = requirejs = function (deps, callback, errback, optional) {
1711 |
1712 | //Find the right context, use default
1713 | var contextName = defContextName,
1714 | context, config;
1715 |
1716 | // Determine if have config object in the call.
1717 | if (!isArray(deps) && typeof deps !== 'string') {
1718 | // deps is a config object
1719 | config = deps;
1720 | if (isArray(callback)) {
1721 | // Adjust args if there are dependencies
1722 | deps = callback;
1723 | callback = errback;
1724 | errback = optional;
1725 | } else {
1726 | deps = [];
1727 | }
1728 | }
1729 |
1730 | if (config && config.context) {
1731 | contextName = config.context;
1732 | }
1733 |
1734 | context = contexts[contextName];
1735 | if (!context) {
1736 | context = contexts[contextName] = req.s.newContext(contextName);
1737 | }
1738 |
1739 | if (config) {
1740 | context.configure(config);
1741 | }
1742 |
1743 | return context.require(deps, callback, errback);
1744 | };
1745 |
1746 | /**
1747 | * Support require.config() to make it easier to cooperate with other
1748 | * AMD loaders on globally agreed names.
1749 | */
1750 | req.config = function (config) {
1751 | return req(config);
1752 | };
1753 |
1754 | /**
1755 | * Export require as a global, but only if it does not already exist.
1756 | */
1757 | if (!require) {
1758 | require = req;
1759 | }
1760 |
1761 | req.version = version;
1762 |
1763 | //Used to filter out dependencies that are already paths.
1764 | req.jsExtRegExp = /^\/|:|\?|\.js$/;
1765 | req.isBrowser = isBrowser;
1766 | s = req.s = {
1767 | contexts: contexts,
1768 | newContext: newContext
1769 | };
1770 |
1771 | //Create default context.
1772 | req({});
1773 |
1774 | //Exports some context-sensitive methods on global require, using
1775 | //default context if no context specified.
1776 | addRequireMethods(req);
1777 |
1778 | if (isBrowser) {
1779 | head = s.head = document.getElementsByTagName('head')[0];
1780 | //If BASE tag is in play, using appendChild is a problem for IE6.
1781 | //When that browser dies, this can be removed. Details in this jQuery bug:
1782 | //http://dev.jquery.com/ticket/2709
1783 | baseElement = document.getElementsByTagName('base')[0];
1784 | if (baseElement) {
1785 | head = s.head = baseElement.parentNode;
1786 | }
1787 | }
1788 |
1789 | /**
1790 | * Any errors that require explicitly generates will be passed to this
1791 | * function. Intercept/override it if you want custom error handling.
1792 | * @param {Error} err the error object.
1793 | */
1794 | req.onError = function (err) {
1795 | throw err;
1796 | };
1797 |
1798 | /**
1799 | * Does the request to load a module for the browser case.
1800 | * Make this a separate function to allow other environments
1801 | * to override it.
1802 | *
1803 | * @param {Object} context the require context to find state.
1804 | * @param {String} moduleName the name of the module.
1805 | * @param {Object} url the URL to the module.
1806 | */
1807 | req.load = function (context, moduleName, url) {
1808 | var config = (context && context.config) || {},
1809 | node;
1810 | if (isBrowser) {
1811 | //In the browser so use a script tag
1812 | node = config.xhtml ?
1813 | document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
1814 | document.createElement('script');
1815 | node.type = config.scriptType || 'text/javascript';
1816 | node.charset = 'utf-8';
1817 | node.async = true;
1818 |
1819 | node.setAttribute('data-requirecontext', context.contextName);
1820 | node.setAttribute('data-requiremodule', moduleName);
1821 |
1822 | //Set up load listener. Test attachEvent first because IE9 has
1823 | //a subtle issue in its addEventListener and script onload firings
1824 | //that do not match the behavior of all other browsers with
1825 | //addEventListener support, which fire the onload event for a
1826 | //script right after the script execution. See:
1827 | //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
1828 | //UNFORTUNATELY Opera implements attachEvent but does not follow the script
1829 | //script execution mode.
1830 | if (node.attachEvent &&
1831 | //Check if node.attachEvent is artificially added by custom script or
1832 | //natively supported by browser
1833 | //read https://github.com/jrburke/requirejs/issues/187
1834 | //if we can NOT find [native code] then it must NOT natively supported.
1835 | //in IE8, node.attachEvent does not have toString()
1836 | //Note the test for "[native code" with no closing brace, see:
1837 | //https://github.com/jrburke/requirejs/issues/273
1838 | !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
1839 | !isOpera) {
1840 | //Probably IE. IE (at least 6-8) do not fire
1841 | //script onload right after executing the script, so
1842 | //we cannot tie the anonymous define call to a name.
1843 | //However, IE reports the script as being in 'interactive'
1844 | //readyState at the time of the define call.
1845 | useInteractive = true;
1846 |
1847 | node.attachEvent('onreadystatechange', context.onScriptLoad);
1848 | //It would be great to add an error handler here to catch
1849 | //404s in IE9+. However, onreadystatechange will fire before
1850 | //the error handler, so that does not help. If addEvenListener
1851 | //is used, then IE will fire error before load, but we cannot
1852 | //use that pathway given the connect.microsoft.com issue
1853 | //mentioned above about not doing the 'script execute,
1854 | //then fire the script load event listener before execute
1855 | //next script' that other browsers do.
1856 | //Best hope: IE10 fixes the issues,
1857 | //and then destroys all installs of IE 6-9.
1858 | //node.attachEvent('onerror', context.onScriptError);
1859 | } else {
1860 | node.addEventListener('load', context.onScriptLoad, false);
1861 | node.addEventListener('error', context.onScriptError, false);
1862 | }
1863 | node.src = url;
1864 |
1865 | //For some cache cases in IE 6-8, the script executes before the end
1866 | //of the appendChild execution, so to tie an anonymous define
1867 | //call to the module name (which is stored on the node), hold on
1868 | //to a reference to this node, but clear after the DOM insertion.
1869 | currentlyAddingScript = node;
1870 | if (baseElement) {
1871 | head.insertBefore(node, baseElement);
1872 | } else {
1873 | head.appendChild(node);
1874 | }
1875 | currentlyAddingScript = null;
1876 |
1877 | return node;
1878 | } else if (isWebWorker) {
1879 | //In a web worker, use importScripts. This is not a very
1880 | //efficient use of importScripts, importScripts will block until
1881 | //its script is downloaded and evaluated. However, if web workers
1882 | //are in play, the expectation that a build has been done so that
1883 | //only one script needs to be loaded anyway. This may need to be
1884 | //reevaluated if other use cases become common.
1885 | importScripts(url);
1886 |
1887 | //Account for anonymous modules
1888 | context.completeLoad(moduleName);
1889 | }
1890 | };
1891 |
1892 | function getInteractiveScript() {
1893 | if (interactiveScript && interactiveScript.readyState === 'interactive') {
1894 | return interactiveScript;
1895 | }
1896 |
1897 | eachReverse(scripts(), function (script) {
1898 | if (script.readyState === 'interactive') {
1899 | return (interactiveScript = script);
1900 | }
1901 | });
1902 | return interactiveScript;
1903 | }
1904 |
1905 | //Look for a data-main script attribute, which could also adjust the baseUrl.
1906 | if (isBrowser) {
1907 | //Figure out baseUrl. Get it from the script tag with require.js in it.
1908 | eachReverse(scripts(), function (script) {
1909 | //Set the 'head' where we can append children by
1910 | //using the script's parent.
1911 | if (!head) {
1912 | head = script.parentNode;
1913 | }
1914 |
1915 | //Look for a data-main attribute to set main script for the page
1916 | //to load. If it is there, the path to data main becomes the
1917 | //baseUrl, if it is not already set.
1918 | dataMain = script.getAttribute('data-main');
1919 | if (dataMain) {
1920 | //Set final baseUrl if there is not already an explicit one.
1921 | if (!cfg.baseUrl) {
1922 | //Pull off the directory of data-main for use as the
1923 | //baseUrl.
1924 | src = dataMain.split('/');
1925 | mainScript = src.pop();
1926 | subPath = src.length ? src.join('/') + '/' : './';
1927 |
1928 | cfg.baseUrl = subPath;
1929 | dataMain = mainScript;
1930 | }
1931 |
1932 | //Strip off any trailing .js since dataMain is now
1933 | //like a module name.
1934 | dataMain = dataMain.replace(jsSuffixRegExp, '');
1935 |
1936 | //Put the data-main script in the files to load.
1937 | cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
1938 |
1939 | return true;
1940 | }
1941 | });
1942 | }
1943 |
1944 | /**
1945 | * The function that handles definitions of modules. Differs from
1946 | * require() in that a string for the module should be the first argument,
1947 | * and the function to execute after dependencies are loaded should
1948 | * return a value to define the module corresponding to the first argument's
1949 | * name.
1950 | */
1951 | define = function (name, deps, callback) {
1952 | var node, context;
1953 |
1954 | //Allow for anonymous functions
1955 | if (typeof name !== 'string') {
1956 | //Adjust args appropriately
1957 | callback = deps;
1958 | deps = name;
1959 | name = null;
1960 | }
1961 |
1962 | //This module may not have dependencies
1963 | if (!isArray(deps)) {
1964 | callback = deps;
1965 | deps = [];
1966 | }
1967 |
1968 | //If no name, and callback is a function, then figure out if it a
1969 | //CommonJS thing with dependencies.
1970 | if (!deps.length && isFunction(callback)) {
1971 | //Remove comments from the callback string,
1972 | //look for require calls, and pull them into the dependencies,
1973 | //but only if there are function args.
1974 | if (callback.length) {
1975 | callback
1976 | .toString()
1977 | .replace(commentRegExp, '')
1978 | .replace(cjsRequireRegExp, function (match, dep) {
1979 | deps.push(dep);
1980 | });
1981 |
1982 | //May be a CommonJS thing even without require calls, but still
1983 | //could use exports, and module. Avoid doing exports and module
1984 | //work though if it just needs require.
1985 | //REQUIRES the function to expect the CommonJS variables in the
1986 | //order listed below.
1987 | deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
1988 | }
1989 | }
1990 |
1991 | //If in IE 6-8 and hit an anonymous define() call, do the interactive
1992 | //work.
1993 | if (useInteractive) {
1994 | node = currentlyAddingScript || getInteractiveScript();
1995 | if (node) {
1996 | if (!name) {
1997 | name = node.getAttribute('data-requiremodule');
1998 | }
1999 | context = contexts[node.getAttribute('data-requirecontext')];
2000 | }
2001 | }
2002 |
2003 | //Always save off evaluating the def call until the script onload handler.
2004 | //This allows multiple modules to be in a file without prematurely
2005 | //tracing dependencies, and allows for anonymous module support,
2006 | //where the module name is not known until the script onload event
2007 | //occurs. If no context, use the global queue, and get it processed
2008 | //in the onscript load callback.
2009 | (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
2010 | };
2011 |
2012 | define.amd = {
2013 | jQuery: true
2014 | };
2015 |
2016 |
2017 | /**
2018 | * Executes the text. Normally just uses eval, but can be modified
2019 | * to use a better, environment-specific call. Only used for transpiling
2020 | * loader plugins, not for plain JS modules.
2021 | * @param {String} text the text to execute/evaluate.
2022 | */
2023 | req.exec = function (text) {
2024 | /*jslint evil: true */
2025 | return eval(text);
2026 | };
2027 |
2028 | //Set up with config info.
2029 | req(cfg);
2030 | }(this));
2031 |
--------------------------------------------------------------------------------
/ModularDemo/Scripts3/require.js:
--------------------------------------------------------------------------------
1 | /** vim: et:ts=4:sw=4:sts=4
2 | * @license RequireJS 2.0.4 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
3 | * Available via the MIT or new BSD license.
4 | * see: http://github.com/jrburke/requirejs for details
5 | */
6 | /*jslint regexp: true, nomen: true */
7 | /*global window, navigator, document, importScripts, jQuery, setTimeout, opera */
8 |
9 | var requirejs, require, define;
10 | (function (global) {
11 | 'use strict';
12 |
13 | var version = '2.0.4',
14 | commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
15 | cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
16 | jsSuffixRegExp = /\.js$/,
17 | currDirRegExp = /^\.\//,
18 | ostring = Object.prototype.toString,
19 | ap = Array.prototype,
20 | aps = ap.slice,
21 | apsp = ap.splice,
22 | isBrowser = !!(typeof window !== 'undefined' && navigator && document),
23 | isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
24 | //PS3 indicates loaded and complete, but need to wait for complete
25 | //specifically. Sequence is 'loading', 'loaded', execution,
26 | // then 'complete'. The UA check is unfortunate, but not sure how
27 | //to feature test w/o causing perf issues.
28 | readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
29 | /^complete$/ : /^(complete|loaded)$/,
30 | defContextName = '_',
31 | //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
32 | isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
33 | contexts = {},
34 | cfg = {},
35 | globalDefQueue = [],
36 | useInteractive = false,
37 | req, s, head, baseElement, dataMain, src,
38 | interactiveScript, currentlyAddingScript, mainScript, subPath;
39 |
40 | function isFunction(it) {
41 | return ostring.call(it) === '[object Function]';
42 | }
43 |
44 | function isArray(it) {
45 | return ostring.call(it) === '[object Array]';
46 | }
47 |
48 | /**
49 | * Helper function for iterating over an array. If the func returns
50 | * a true value, it will break out of the loop.
51 | */
52 | function each(ary, func) {
53 | if (ary) {
54 | var i;
55 | for (i = 0; i < ary.length; i += 1) {
56 | if (ary[i] && func(ary[i], i, ary)) {
57 | break;
58 | }
59 | }
60 | }
61 | }
62 |
63 | /**
64 | * Helper function for iterating over an array backwards. If the func
65 | * returns a true value, it will break out of the loop.
66 | */
67 | function eachReverse(ary, func) {
68 | if (ary) {
69 | var i;
70 | for (i = ary.length - 1; i > -1; i -= 1) {
71 | if (ary[i] && func(ary[i], i, ary)) {
72 | break;
73 | }
74 | }
75 | }
76 | }
77 |
78 | function hasProp(obj, prop) {
79 | return obj.hasOwnProperty(prop);
80 | }
81 |
82 | /**
83 | * Cycles over properties in an object and calls a function for each
84 | * property value. If the function returns a truthy value, then the
85 | * iteration is stopped.
86 | */
87 | function eachProp(obj, func) {
88 | var prop;
89 | for (prop in obj) {
90 | if (obj.hasOwnProperty(prop)) {
91 | if (func(obj[prop], prop)) {
92 | break;
93 | }
94 | }
95 | }
96 | }
97 |
98 | /**
99 | * Simple function to mix in properties from source into target,
100 | * but only if target does not already have a property of the same name.
101 | * This is not robust in IE for transferring methods that match
102 | * Object.prototype names, but the uses of mixin here seem unlikely to
103 | * trigger a problem related to that.
104 | */
105 | function mixin(target, source, force, deepStringMixin) {
106 | if (source) {
107 | eachProp(source, function (value, prop) {
108 | if (force || !hasProp(target, prop)) {
109 | if (deepStringMixin && typeof value !== 'string') {
110 | if (!target[prop]) {
111 | target[prop] = {};
112 | }
113 | mixin(target[prop], value, force, deepStringMixin);
114 | } else {
115 | target[prop] = value;
116 | }
117 | }
118 | });
119 | }
120 | return target;
121 | }
122 |
123 | //Similar to Function.prototype.bind, but the 'this' object is specified
124 | //first, since it is easier to read/figure out what 'this' will be.
125 | function bind(obj, fn) {
126 | return function () {
127 | return fn.apply(obj, arguments);
128 | };
129 | }
130 |
131 | function scripts() {
132 | return document.getElementsByTagName('script');
133 | }
134 |
135 | //Allow getting a global that expressed in
136 | //dot notation, like 'a.b.c'.
137 | function getGlobal(value) {
138 | if (!value) {
139 | return value;
140 | }
141 | var g = global;
142 | each(value.split('.'), function (part) {
143 | g = g[part];
144 | });
145 | return g;
146 | }
147 |
148 | function makeContextModuleFunc(func, relMap, enableBuildCallback) {
149 | return function () {
150 | //A version of a require function that passes a moduleName
151 | //value for items that may need to
152 | //look up paths relative to the moduleName
153 | var args = aps.call(arguments, 0), lastArg;
154 | if (enableBuildCallback &&
155 | isFunction((lastArg = args[args.length - 1]))) {
156 | lastArg.__requireJsBuild = true;
157 | }
158 | args.push(relMap);
159 | return func.apply(null, args);
160 | };
161 | }
162 |
163 | function addRequireMethods(req, context, relMap) {
164 | each([
165 | ['toUrl'],
166 | ['undef'],
167 | ['defined', 'requireDefined'],
168 | ['specified', 'requireSpecified']
169 | ], function (item) {
170 | var prop = item[1] || item[0];
171 | req[item[0]] = context ? makeContextModuleFunc(context[prop], relMap) :
172 | //If no context, then use default context. Reference from
173 | //contexts instead of early binding to default context, so
174 | //that during builds, the latest instance of the default
175 | //context with its config gets used.
176 | function () {
177 | var ctx = contexts[defContextName];
178 | return ctx[prop].apply(ctx, arguments);
179 | };
180 | });
181 | }
182 |
183 | /**
184 | * Constructs an error with a pointer to an URL with more information.
185 | * @param {String} id the error ID that maps to an ID on a web page.
186 | * @param {String} message human readable error.
187 | * @param {Error} [err] the original error, if there is one.
188 | *
189 | * @returns {Error}
190 | */
191 | function makeError(id, msg, err, requireModules) {
192 | var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
193 | e.requireType = id;
194 | e.requireModules = requireModules;
195 | if (err) {
196 | e.originalError = err;
197 | }
198 | return e;
199 | }
200 |
201 | if (typeof define !== 'undefined') {
202 | //If a define is already in play via another AMD loader,
203 | //do not overwrite.
204 | return;
205 | }
206 |
207 | if (typeof requirejs !== 'undefined') {
208 | if (isFunction(requirejs)) {
209 | //Do not overwrite and existing requirejs instance.
210 | return;
211 | }
212 | cfg = requirejs;
213 | requirejs = undefined;
214 | }
215 |
216 | //Allow for a require config object
217 | if (typeof require !== 'undefined' && !isFunction(require)) {
218 | //assume it is a config object.
219 | cfg = require;
220 | require = undefined;
221 | }
222 |
223 | function newContext(contextName) {
224 | var config = {
225 | waitSeconds: 7,
226 | baseUrl: './',
227 | paths: {},
228 | pkgs: {},
229 | shim: {}
230 | },
231 | registry = {},
232 | undefEvents = {},
233 | defQueue = [],
234 | defined = {},
235 | urlFetched = {},
236 | requireCounter = 1,
237 | unnormalizedCounter = 1,
238 | //Used to track the order in which modules
239 | //should be executed, by the order they
240 | //load. Important for consistent cycle resolution
241 | //behavior.
242 | waitAry = [],
243 | inCheckLoaded, Module, context, handlers,
244 | checkLoadedTimeoutId;
245 |
246 | /**
247 | * Trims the . and .. from an array of path segments.
248 | * It will keep a leading path segment if a .. will become
249 | * the first path segment, to help with module name lookups,
250 | * which act like paths, but can be remapped. But the end result,
251 | * all paths that use this function should look normalized.
252 | * NOTE: this method MODIFIES the input array.
253 | * @param {Array} ary the array of path segments.
254 | */
255 | function trimDots(ary) {
256 | var i, part;
257 | for (i = 0; ary[i]; i+= 1) {
258 | part = ary[i];
259 | if (part === '.') {
260 | ary.splice(i, 1);
261 | i -= 1;
262 | } else if (part === '..') {
263 | if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
264 | //End of the line. Keep at least one non-dot
265 | //path segment at the front so it can be mapped
266 | //correctly to disk. Otherwise, there is likely
267 | //no path mapping for a path starting with '..'.
268 | //This can still fail, but catches the most reasonable
269 | //uses of ..
270 | break;
271 | } else if (i > 0) {
272 | ary.splice(i - 1, 2);
273 | i -= 2;
274 | }
275 | }
276 | }
277 | }
278 |
279 | /**
280 | * Given a relative module name, like ./something, normalize it to
281 | * a real name that can be mapped to a path.
282 | * @param {String} name the relative name
283 | * @param {String} baseName a real name that the name arg is relative
284 | * to.
285 | * @param {Boolean} applyMap apply the map config to the value. Should
286 | * only be done if this normalization is for a dependency ID.
287 | * @returns {String} normalized name
288 | */
289 | function normalize(name, baseName, applyMap) {
290 | var baseParts = baseName && baseName.split('/'),
291 | normalizedBaseParts = baseParts,
292 | map = config.map,
293 | starMap = map && map['*'],
294 | pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
295 | foundMap;
296 |
297 | //Adjust any relative paths.
298 | if (name && name.charAt(0) === '.') {
299 | //If have a base name, try to normalize against it,
300 | //otherwise, assume it is a top-level require that will
301 | //be relative to baseUrl in the end.
302 | if (baseName) {
303 | if (config.pkgs[baseName]) {
304 | //If the baseName is a package name, then just treat it as one
305 | //name to concat the name with.
306 | normalizedBaseParts = baseParts = [baseName];
307 | } else {
308 | //Convert baseName to array, and lop off the last part,
309 | //so that . matches that 'directory' and not name of the baseName's
310 | //module. For instance, baseName of 'one/two/three', maps to
311 | //'one/two/three.js', but we want the directory, 'one/two' for
312 | //this normalization.
313 | normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
314 | }
315 |
316 | name = normalizedBaseParts.concat(name.split('/'));
317 | trimDots(name);
318 |
319 | //Some use of packages may use a . path to reference the
320 | //'main' module name, so normalize for that.
321 | pkgConfig = config.pkgs[(pkgName = name[0])];
322 | name = name.join('/');
323 | if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
324 | name = pkgName;
325 | }
326 | } else if (name.indexOf('./') === 0) {
327 | // No baseName, so this is ID is resolved relative
328 | // to baseUrl, pull off the leading dot.
329 | name = name.substring(2);
330 | }
331 | }
332 |
333 | //Apply map config if available.
334 | if (applyMap && (baseParts || starMap) && map) {
335 | nameParts = name.split('/');
336 |
337 | for (i = nameParts.length; i > 0; i -= 1) {
338 | nameSegment = nameParts.slice(0, i).join('/');
339 |
340 | if (baseParts) {
341 | //Find the longest baseName segment match in the config.
342 | //So, do joins on the biggest to smallest lengths of baseParts.
343 | for (j = baseParts.length; j > 0; j -= 1) {
344 | mapValue = map[baseParts.slice(0, j).join('/')];
345 |
346 | //baseName segment has config, find if it has one for
347 | //this name.
348 | if (mapValue) {
349 | mapValue = mapValue[nameSegment];
350 | if (mapValue) {
351 | //Match, update name to the new value.
352 | foundMap = mapValue;
353 | break;
354 | }
355 | }
356 | }
357 | }
358 |
359 | if (!foundMap && starMap && starMap[nameSegment]) {
360 | foundMap = starMap[nameSegment];
361 | }
362 |
363 | if (foundMap) {
364 | nameParts.splice(0, i, foundMap);
365 | name = nameParts.join('/');
366 | break;
367 | }
368 | }
369 | }
370 |
371 | return name;
372 | }
373 |
374 | function removeScript(name) {
375 | if (isBrowser) {
376 | each(scripts(), function (scriptNode) {
377 | if (scriptNode.getAttribute('data-requiremodule') === name &&
378 | scriptNode.getAttribute('data-requirecontext') === context.contextName) {
379 | scriptNode.parentNode.removeChild(scriptNode);
380 | return true;
381 | }
382 | });
383 | }
384 | }
385 |
386 | function hasPathFallback(id) {
387 | var pathConfig = config.paths[id];
388 | if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
389 | removeScript(id);
390 | //Pop off the first array value, since it failed, and
391 | //retry
392 | pathConfig.shift();
393 | context.undef(id);
394 | context.require([id]);
395 | return true;
396 | }
397 | }
398 |
399 | /**
400 | * Creates a module mapping that includes plugin prefix, module
401 | * name, and path. If parentModuleMap is provided it will
402 | * also normalize the name via require.normalize()
403 | *
404 | * @param {String} name the module name
405 | * @param {String} [parentModuleMap] parent module map
406 | * for the module name, used to resolve relative names.
407 | * @param {Boolean} isNormalized: is the ID already normalized.
408 | * This is true if this call is done for a define() module ID.
409 | * @param {Boolean} applyMap: apply the map config to the ID.
410 | * Should only be true if this map is for a dependency.
411 | *
412 | * @returns {Object}
413 | */
414 | function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
415 | var index = name ? name.indexOf('!') : -1,
416 | prefix = null,
417 | parentName = parentModuleMap ? parentModuleMap.name : null,
418 | originalName = name,
419 | isDefine = true,
420 | normalizedName = '',
421 | url, pluginModule, suffix;
422 |
423 | //If no name, then it means it is a require call, generate an
424 | //internal name.
425 | if (!name) {
426 | isDefine = false;
427 | name = '_@r' + (requireCounter += 1);
428 | }
429 |
430 | if (index !== -1) {
431 | prefix = name.substring(0, index);
432 | name = name.substring(index + 1, name.length);
433 | }
434 |
435 | if (prefix) {
436 | prefix = normalize(prefix, parentName, applyMap);
437 | pluginModule = defined[prefix];
438 | }
439 |
440 | //Account for relative paths if there is a base name.
441 | if (name) {
442 | if (prefix) {
443 | if (pluginModule && pluginModule.normalize) {
444 | //Plugin is loaded, use its normalize method.
445 | normalizedName = pluginModule.normalize(name, function (name) {
446 | return normalize(name, parentName, applyMap);
447 | });
448 | } else {
449 | normalizedName = normalize(name, parentName, applyMap);
450 | }
451 | } else {
452 | //A regular module.
453 | normalizedName = normalize(name, parentName, applyMap);
454 | url = context.nameToUrl(normalizedName);
455 | }
456 | }
457 |
458 | //If the id is a plugin id that cannot be determined if it needs
459 | //normalization, stamp it with a unique ID so two matching relative
460 | //ids that may conflict can be separate.
461 | suffix = prefix && !pluginModule && !isNormalized ?
462 | '_unnormalized' + (unnormalizedCounter += 1) :
463 | '';
464 |
465 | return {
466 | prefix: prefix,
467 | name: normalizedName,
468 | parentMap: parentModuleMap,
469 | unnormalized: !!suffix,
470 | url: url,
471 | originalName: originalName,
472 | isDefine: isDefine,
473 | id: (prefix ?
474 | prefix + '!' + normalizedName :
475 | normalizedName) + suffix
476 | };
477 | }
478 |
479 | function getModule(depMap) {
480 | var id = depMap.id,
481 | mod = registry[id];
482 |
483 | if (!mod) {
484 | mod = registry[id] = new context.Module(depMap);
485 | }
486 |
487 | return mod;
488 | }
489 |
490 | function on(depMap, name, fn) {
491 | var id = depMap.id,
492 | mod = registry[id];
493 |
494 | if (hasProp(defined, id) &&
495 | (!mod || mod.defineEmitComplete)) {
496 | if (name === 'defined') {
497 | fn(defined[id]);
498 | }
499 | } else {
500 | getModule(depMap).on(name, fn);
501 | }
502 | }
503 |
504 | function onError(err, errback) {
505 | var ids = err.requireModules,
506 | notified = false;
507 |
508 | if (errback) {
509 | errback(err);
510 | } else {
511 | each(ids, function (id) {
512 | var mod = registry[id];
513 | if (mod) {
514 | //Set error on module, so it skips timeout checks.
515 | mod.error = err;
516 | if (mod.events.error) {
517 | notified = true;
518 | mod.emit('error', err);
519 | }
520 | }
521 | });
522 |
523 | if (!notified) {
524 | req.onError(err);
525 | }
526 | }
527 | }
528 |
529 | /**
530 | * Internal method to transfer globalQueue items to this context's
531 | * defQueue.
532 | */
533 | function takeGlobalQueue() {
534 | //Push all the globalDefQueue items into the context's defQueue
535 | if (globalDefQueue.length) {
536 | //Array splice in the values since the context code has a
537 | //local var ref to defQueue, so cannot just reassign the one
538 | //on context.
539 | apsp.apply(defQueue,
540 | [defQueue.length - 1, 0].concat(globalDefQueue));
541 | globalDefQueue = [];
542 | }
543 | }
544 |
545 | /**
546 | * Helper function that creates a require function object to give to
547 | * modules that ask for it as a dependency. It needs to be specific
548 | * per module because of the implication of path mappings that may
549 | * need to be relative to the module name.
550 | */
551 | function makeRequire(mod, enableBuildCallback, altRequire) {
552 | var relMap = mod && mod.map,
553 | modRequire = makeContextModuleFunc(altRequire || context.require,
554 | relMap,
555 | enableBuildCallback);
556 |
557 | addRequireMethods(modRequire, context, relMap);
558 | modRequire.isBrowser = isBrowser;
559 |
560 | return modRequire;
561 | }
562 |
563 | handlers = {
564 | 'require': function (mod) {
565 | return makeRequire(mod);
566 | },
567 | 'exports': function (mod) {
568 | mod.usingExports = true;
569 | if (mod.map.isDefine) {
570 | return (mod.exports = defined[mod.map.id] = {});
571 | }
572 | },
573 | 'module': function (mod) {
574 | return (mod.module = {
575 | id: mod.map.id,
576 | uri: mod.map.url,
577 | config: function () {
578 | return (config.config && config.config[mod.map.id]) || {};
579 | },
580 | exports: defined[mod.map.id]
581 | });
582 | }
583 | };
584 |
585 | function removeWaiting(id) {
586 | //Clean up machinery used for waiting modules.
587 | delete registry[id];
588 |
589 | each(waitAry, function (mod, i) {
590 | if (mod.map.id === id) {
591 | waitAry.splice(i, 1);
592 | if (!mod.defined) {
593 | context.waitCount -= 1;
594 | }
595 | return true;
596 | }
597 | });
598 | }
599 |
600 | function findCycle(mod, traced) {
601 | var id = mod.map.id,
602 | depArray = mod.depMaps,
603 | foundModule;
604 |
605 | //Do not bother with unitialized modules or not yet enabled
606 | //modules.
607 | if (!mod.inited) {
608 | return;
609 | }
610 |
611 | //Found the cycle.
612 | if (traced[id]) {
613 | return mod;
614 | }
615 |
616 | traced[id] = true;
617 |
618 | //Trace through the dependencies.
619 | each(depArray, function (depMap) {
620 | var depId = depMap.id,
621 | depMod = registry[depId];
622 |
623 | if (!depMod) {
624 | return;
625 | }
626 |
627 | if (!depMod.inited || !depMod.enabled) {
628 | //Dependency is not inited, so this cannot
629 | //be used to determine a cycle.
630 | foundModule = null;
631 | delete traced[id];
632 | return true;
633 | }
634 |
635 | //mixin traced to a new object for each dependency, so that
636 | //sibling dependencies in this object to not generate a
637 | //false positive match on a cycle. Ideally an Object.create
638 | //type of prototype delegation would be used here, but
639 | //optimizing for file size vs. execution speed since hopefully
640 | //the trees are small for circular dependency scans relative
641 | //to the full app perf.
642 | return (foundModule = findCycle(depMod, mixin({}, traced)));
643 | });
644 |
645 | return foundModule;
646 | }
647 |
648 | function forceExec(mod, traced, uninited) {
649 | var id = mod.map.id,
650 | depArray = mod.depMaps;
651 |
652 | if (!mod.inited || !mod.map.isDefine) {
653 | return;
654 | }
655 |
656 | if (traced[id]) {
657 | return defined[id];
658 | }
659 |
660 | traced[id] = mod;
661 |
662 | each(depArray, function(depMap) {
663 | var depId = depMap.id,
664 | depMod = registry[depId],
665 | value;
666 |
667 | if (handlers[depId]) {
668 | return;
669 | }
670 |
671 | if (depMod) {
672 | if (!depMod.inited || !depMod.enabled) {
673 | //Dependency is not inited,
674 | //so this module cannot be
675 | //given a forced value yet.
676 | uninited[id] = true;
677 | return;
678 | }
679 |
680 | //Get the value for the current dependency
681 | value = forceExec(depMod, traced, uninited);
682 |
683 | //Even with forcing it may not be done,
684 | //in particular if the module is waiting
685 | //on a plugin resource.
686 | if (!uninited[depId]) {
687 | mod.defineDepById(depId, value);
688 | }
689 | }
690 | });
691 |
692 | mod.check(true);
693 |
694 | return defined[id];
695 | }
696 |
697 | function modCheck(mod) {
698 | mod.check();
699 | }
700 |
701 | function checkLoaded() {
702 | var waitInterval = config.waitSeconds * 1000,
703 | //It is possible to disable the wait interval by using waitSeconds of 0.
704 | expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
705 | noLoads = [],
706 | stillLoading = false,
707 | needCycleCheck = true,
708 | map, modId, err, usingPathFallback;
709 |
710 | //Do not bother if this call was a result of a cycle break.
711 | if (inCheckLoaded) {
712 | return;
713 | }
714 |
715 | inCheckLoaded = true;
716 |
717 | //Figure out the state of all the modules.
718 | eachProp(registry, function (mod) {
719 | map = mod.map;
720 | modId = map.id;
721 |
722 | //Skip things that are not enabled or in error state.
723 | if (!mod.enabled) {
724 | return;
725 | }
726 |
727 | if (!mod.error) {
728 | //If the module should be executed, and it has not
729 | //been inited and time is up, remember it.
730 | if (!mod.inited && expired) {
731 | if (hasPathFallback(modId)) {
732 | usingPathFallback = true;
733 | stillLoading = true;
734 | } else {
735 | noLoads.push(modId);
736 | removeScript(modId);
737 | }
738 | } else if (!mod.inited && mod.fetched && map.isDefine) {
739 | stillLoading = true;
740 | if (!map.prefix) {
741 | //No reason to keep looking for unfinished
742 | //loading. If the only stillLoading is a
743 | //plugin resource though, keep going,
744 | //because it may be that a plugin resource
745 | //is waiting on a non-plugin cycle.
746 | return (needCycleCheck = false);
747 | }
748 | }
749 | }
750 | });
751 |
752 | if (expired && noLoads.length) {
753 | //If wait time expired, throw error of unloaded modules.
754 | err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
755 | err.contextName = context.contextName;
756 | return onError(err);
757 | }
758 |
759 | //Not expired, check for a cycle.
760 | if (needCycleCheck) {
761 |
762 | each(waitAry, function (mod) {
763 | if (mod.defined) {
764 | return;
765 | }
766 |
767 | var cycleMod = findCycle(mod, {}),
768 | traced = {};
769 |
770 | if (cycleMod) {
771 | forceExec(cycleMod, traced, {});
772 |
773 | //traced modules may have been
774 | //removed from the registry, but
775 | //their listeners still need to
776 | //be called.
777 | eachProp(traced, modCheck);
778 | }
779 | });
780 |
781 | //Now that dependencies have
782 | //been satisfied, trigger the
783 | //completion check that then
784 | //notifies listeners.
785 | eachProp(registry, modCheck);
786 | }
787 |
788 | //If still waiting on loads, and the waiting load is something
789 | //other than a plugin resource, or there are still outstanding
790 | //scripts, then just try back later.
791 | if ((!expired || usingPathFallback) && stillLoading) {
792 | //Something is still waiting to load. Wait for it, but only
793 | //if a timeout is not already in effect.
794 | if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
795 | checkLoadedTimeoutId = setTimeout(function () {
796 | checkLoadedTimeoutId = 0;
797 | checkLoaded();
798 | }, 50);
799 | }
800 | }
801 |
802 | inCheckLoaded = false;
803 | }
804 |
805 | Module = function (map) {
806 | this.events = undefEvents[map.id] || {};
807 | this.map = map;
808 | this.shim = config.shim[map.id];
809 | this.depExports = [];
810 | this.depMaps = [];
811 | this.depMatched = [];
812 | this.pluginMaps = {};
813 | this.depCount = 0;
814 |
815 | /* this.exports this.factory
816 | this.depMaps = [],
817 | this.enabled, this.fetched
818 | */
819 | };
820 |
821 | Module.prototype = {
822 | init: function(depMaps, factory, errback, options) {
823 | options = options || {};
824 |
825 | //Do not do more inits if already done. Can happen if there
826 | //are multiple define calls for the same module. That is not
827 | //a normal, common case, but it is also not unexpected.
828 | if (this.inited) {
829 | return;
830 | }
831 |
832 | this.factory = factory;
833 |
834 | if (errback) {
835 | //Register for errors on this module.
836 | this.on('error', errback);
837 | } else if (this.events.error) {
838 | //If no errback already, but there are error listeners
839 | //on this module, set up an errback to pass to the deps.
840 | errback = bind(this, function (err) {
841 | this.emit('error', err);
842 | });
843 | }
844 |
845 | //Do a copy of the dependency array, so that
846 | //source inputs are not modified. For example
847 | //"shim" deps are passed in here directly, and
848 | //doing a direct modification of the depMaps array
849 | //would affect that config.
850 | this.depMaps = depMaps && depMaps.slice(0);
851 | this.depMaps.rjsSkipMap = depMaps.rjsSkipMap;
852 |
853 | this.errback = errback;
854 |
855 | //Indicate this module has be initialized
856 | this.inited = true;
857 |
858 | this.ignore = options.ignore;
859 |
860 | //Could have option to init this module in enabled mode,
861 | //or could have been previously marked as enabled. However,
862 | //the dependencies are not known until init is called. So
863 | //if enabled previously, now trigger dependencies as enabled.
864 | if (options.enabled || this.enabled) {
865 | //Enable this module and dependencies.
866 | //Will call this.check()
867 | this.enable();
868 | } else {
869 | this.check();
870 | }
871 | },
872 |
873 | defineDepById: function (id, depExports) {
874 | var i;
875 |
876 | //Find the index for this dependency.
877 | each(this.depMaps, function (map, index) {
878 | if (map.id === id) {
879 | i = index;
880 | return true;
881 | }
882 | });
883 |
884 | return this.defineDep(i, depExports);
885 | },
886 |
887 | defineDep: function (i, depExports) {
888 | //Because of cycles, defined callback for a given
889 | //export can be called more than once.
890 | if (!this.depMatched[i]) {
891 | this.depMatched[i] = true;
892 | this.depCount -= 1;
893 | this.depExports[i] = depExports;
894 | }
895 | },
896 |
897 | fetch: function () {
898 | if (this.fetched) {
899 | return;
900 | }
901 | this.fetched = true;
902 |
903 | context.startTime = (new Date()).getTime();
904 |
905 | var map = this.map;
906 |
907 | //If the manager is for a plugin managed resource,
908 | //ask the plugin to load it now.
909 | if (this.shim) {
910 | makeRequire(this, true)(this.shim.deps || [], bind(this, function () {
911 | return map.prefix ? this.callPlugin() : this.load();
912 | }));
913 | } else {
914 | //Regular dependency.
915 | return map.prefix ? this.callPlugin() : this.load();
916 | }
917 | },
918 |
919 | load: function() {
920 | var url = this.map.url;
921 |
922 | //Regular dependency.
923 | if (!urlFetched[url]) {
924 | urlFetched[url] = true;
925 | context.load(this.map.id, url);
926 | }
927 | },
928 |
929 | /**
930 | * Checks is the module is ready to define itself, and if so,
931 | * define it. If the silent argument is true, then it will just
932 | * define, but not notify listeners, and not ask for a context-wide
933 | * check of all loaded modules. That is useful for cycle breaking.
934 | */
935 | check: function (silent) {
936 | if (!this.enabled || this.enabling) {
937 | return;
938 | }
939 |
940 | var id = this.map.id,
941 | depExports = this.depExports,
942 | exports = this.exports,
943 | factory = this.factory,
944 | err, cjsModule;
945 |
946 | if (!this.inited) {
947 | this.fetch();
948 | } else if (this.error) {
949 | this.emit('error', this.error);
950 | } else if (!this.defining) {
951 | //The factory could trigger another require call
952 | //that would result in checking this module to
953 | //define itself again. If already in the process
954 | //of doing that, skip this work.
955 | this.defining = true;
956 |
957 | if (this.depCount < 1 && !this.defined) {
958 | if (isFunction(factory)) {
959 | //If there is an error listener, favor passing
960 | //to that instead of throwing an error.
961 | if (this.events.error) {
962 | try {
963 | exports = context.execCb(id, factory, depExports, exports);
964 | } catch (e) {
965 | err = e;
966 | }
967 | } else {
968 | exports = context.execCb(id, factory, depExports, exports);
969 | }
970 |
971 | if (this.map.isDefine) {
972 | //If setting exports via 'module' is in play,
973 | //favor that over return value and exports. After that,
974 | //favor a non-undefined return value over exports use.
975 | cjsModule = this.module;
976 | if (cjsModule &&
977 | cjsModule.exports !== undefined &&
978 | //Make sure it is not already the exports value
979 | cjsModule.exports !== this.exports) {
980 | exports = cjsModule.exports;
981 | } else if (exports === undefined && this.usingExports) {
982 | //exports already set the defined value.
983 | exports = this.exports;
984 | }
985 | }
986 |
987 | if (err) {
988 | err.requireMap = this.map;
989 | err.requireModules = [this.map.id];
990 | err.requireType = 'define';
991 | return onError((this.error = err));
992 | }
993 |
994 | } else {
995 | //Just a literal value
996 | exports = factory;
997 | }
998 |
999 | this.exports = exports;
1000 |
1001 | if (this.map.isDefine && !this.ignore) {
1002 | defined[id] = exports;
1003 |
1004 | if (req.onResourceLoad) {
1005 | req.onResourceLoad(context, this.map, this.depMaps);
1006 | }
1007 | }
1008 |
1009 | //Clean up
1010 | delete registry[id];
1011 |
1012 | this.defined = true;
1013 | context.waitCount -= 1;
1014 | if (context.waitCount === 0) {
1015 | //Clear the wait array used for cycles.
1016 | waitAry = [];
1017 | }
1018 | }
1019 |
1020 | //Finished the define stage. Allow calling check again
1021 | //to allow define notifications below in the case of a
1022 | //cycle.
1023 | this.defining = false;
1024 |
1025 | if (!silent) {
1026 | if (this.defined && !this.defineEmitted) {
1027 | this.defineEmitted = true;
1028 | this.emit('defined', this.exports);
1029 | this.defineEmitComplete = true;
1030 | }
1031 | }
1032 | }
1033 | },
1034 |
1035 | callPlugin: function() {
1036 | var map = this.map,
1037 | id = map.id,
1038 | pluginMap = makeModuleMap(map.prefix, null, false, true);
1039 |
1040 | on(pluginMap, 'defined', bind(this, function (plugin) {
1041 | var name = this.map.name,
1042 | parentName = this.map.parentMap ? this.map.parentMap.name : null,
1043 | load, normalizedMap, normalizedMod;
1044 |
1045 | //If current map is not normalized, wait for that
1046 | //normalized name to load instead of continuing.
1047 | if (this.map.unnormalized) {
1048 | //Normalize the ID if the plugin allows it.
1049 | if (plugin.normalize) {
1050 | name = plugin.normalize(name, function (name) {
1051 | return normalize(name, parentName, true);
1052 | }) || '';
1053 | }
1054 |
1055 | normalizedMap = makeModuleMap(map.prefix + '!' + name,
1056 | this.map.parentMap,
1057 | false,
1058 | true);
1059 | on(normalizedMap,
1060 | 'defined', bind(this, function (value) {
1061 | this.init([], function () { return value; }, null, {
1062 | enabled: true,
1063 | ignore: true
1064 | });
1065 | }));
1066 | normalizedMod = registry[normalizedMap.id];
1067 | if (normalizedMod) {
1068 | if (this.events.error) {
1069 | normalizedMod.on('error', bind(this, function (err) {
1070 | this.emit('error', err);
1071 | }));
1072 | }
1073 | normalizedMod.enable();
1074 | }
1075 |
1076 | return;
1077 | }
1078 |
1079 | load = bind(this, function (value) {
1080 | this.init([], function () { return value; }, null, {
1081 | enabled: true
1082 | });
1083 | });
1084 |
1085 | load.error = bind(this, function (err) {
1086 | this.inited = true;
1087 | this.error = err;
1088 | err.requireModules = [id];
1089 |
1090 | //Remove temp unnormalized modules for this module,
1091 | //since they will never be resolved otherwise now.
1092 | eachProp(registry, function (mod) {
1093 | if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
1094 | removeWaiting(mod.map.id);
1095 | }
1096 | });
1097 |
1098 | onError(err);
1099 | });
1100 |
1101 | //Allow plugins to load other code without having to know the
1102 | //context or how to 'complete' the load.
1103 | load.fromText = function (moduleName, text) {
1104 | /*jslint evil: true */
1105 | var hasInteractive = useInteractive;
1106 |
1107 | //Turn off interactive script matching for IE for any define
1108 | //calls in the text, then turn it back on at the end.
1109 | if (hasInteractive) {
1110 | useInteractive = false;
1111 | }
1112 |
1113 | //Prime the system by creating a module instance for
1114 | //it.
1115 | getModule(makeModuleMap(moduleName));
1116 |
1117 | req.exec(text);
1118 |
1119 | if (hasInteractive) {
1120 | useInteractive = true;
1121 | }
1122 |
1123 | //Support anonymous modules.
1124 | context.completeLoad(moduleName);
1125 | };
1126 |
1127 | //Use parentName here since the plugin's name is not reliable,
1128 | //could be some weird string with no path that actually wants to
1129 | //reference the parentName's path.
1130 | plugin.load(map.name, makeRequire(map.parentMap, true, function (deps, cb) {
1131 | deps.rjsSkipMap = true;
1132 | return context.require(deps, cb);
1133 | }), load, config);
1134 | }));
1135 |
1136 | context.enable(pluginMap, this);
1137 | this.pluginMaps[pluginMap.id] = pluginMap;
1138 | },
1139 |
1140 | enable: function () {
1141 | this.enabled = true;
1142 |
1143 | if (!this.waitPushed) {
1144 | waitAry.push(this);
1145 | context.waitCount += 1;
1146 | this.waitPushed = true;
1147 | }
1148 |
1149 | //Set flag mentioning that the module is enabling,
1150 | //so that immediate calls to the defined callbacks
1151 | //for dependencies do not trigger inadvertent load
1152 | //with the depCount still being zero.
1153 | this.enabling = true;
1154 |
1155 | //Enable each dependency
1156 | each(this.depMaps, bind(this, function (depMap, i) {
1157 | var id, mod, handler;
1158 |
1159 | if (typeof depMap === 'string') {
1160 | //Dependency needs to be converted to a depMap
1161 | //and wired up to this module.
1162 | depMap = makeModuleMap(depMap,
1163 | (this.map.isDefine ? this.map : this.map.parentMap),
1164 | false,
1165 | !this.depMaps.rjsSkipMap);
1166 | this.depMaps[i] = depMap;
1167 |
1168 | handler = handlers[depMap.id];
1169 |
1170 | if (handler) {
1171 | this.depExports[i] = handler(this);
1172 | return;
1173 | }
1174 |
1175 | this.depCount += 1;
1176 |
1177 | on(depMap, 'defined', bind(this, function (depExports) {
1178 | this.defineDep(i, depExports);
1179 | this.check();
1180 | }));
1181 |
1182 | if (this.errback) {
1183 | on(depMap, 'error', this.errback);
1184 | }
1185 | }
1186 |
1187 | id = depMap.id;
1188 | mod = registry[id];
1189 |
1190 | //Skip special modules like 'require', 'exports', 'module'
1191 | //Also, don't call enable if it is already enabled,
1192 | //important in circular dependency cases.
1193 | if (!handlers[id] && mod && !mod.enabled) {
1194 | context.enable(depMap, this);
1195 | }
1196 | }));
1197 |
1198 | //Enable each plugin that is used in
1199 | //a dependency
1200 | eachProp(this.pluginMaps, bind(this, function (pluginMap) {
1201 | var mod = registry[pluginMap.id];
1202 | if (mod && !mod.enabled) {
1203 | context.enable(pluginMap, this);
1204 | }
1205 | }));
1206 |
1207 | this.enabling = false;
1208 |
1209 | this.check();
1210 | },
1211 |
1212 | on: function(name, cb) {
1213 | var cbs = this.events[name];
1214 | if (!cbs) {
1215 | cbs = this.events[name] = [];
1216 | }
1217 | cbs.push(cb);
1218 | },
1219 |
1220 | emit: function (name, evt) {
1221 | each(this.events[name], function (cb) {
1222 | cb(evt);
1223 | });
1224 | if (name === 'error') {
1225 | //Now that the error handler was triggered, remove
1226 | //the listeners, since this broken Module instance
1227 | //can stay around for a while in the registry/waitAry.
1228 | delete this.events[name];
1229 | }
1230 | }
1231 | };
1232 |
1233 | function callGetModule(args) {
1234 | getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
1235 | }
1236 |
1237 | function removeListener(node, func, name, ieName) {
1238 | //Favor detachEvent because of IE9
1239 | //issue, see attachEvent/addEventListener comment elsewhere
1240 | //in this file.
1241 | if (node.detachEvent && !isOpera) {
1242 | //Probably IE. If not it will throw an error, which will be
1243 | //useful to know.
1244 | if (ieName) {
1245 | node.detachEvent(ieName, func);
1246 | }
1247 | } else {
1248 | node.removeEventListener(name, func, false);
1249 | }
1250 | }
1251 |
1252 | /**
1253 | * Given an event from a script node, get the requirejs info from it,
1254 | * and then removes the event listeners on the node.
1255 | * @param {Event} evt
1256 | * @returns {Object}
1257 | */
1258 | function getScriptData(evt) {
1259 | //Using currentTarget instead of target for Firefox 2.0's sake. Not
1260 | //all old browsers will be supported, but this one was easy enough
1261 | //to support and still makes sense.
1262 | var node = evt.currentTarget || evt.srcElement;
1263 |
1264 | //Remove the listeners once here.
1265 | removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
1266 | removeListener(node, context.onScriptError, 'error');
1267 |
1268 | return {
1269 | node: node,
1270 | id: node && node.getAttribute('data-requiremodule')
1271 | };
1272 | }
1273 |
1274 | return (context = {
1275 | config: config,
1276 | contextName: contextName,
1277 | registry: registry,
1278 | defined: defined,
1279 | urlFetched: urlFetched,
1280 | waitCount: 0,
1281 | defQueue: defQueue,
1282 | Module: Module,
1283 | makeModuleMap: makeModuleMap,
1284 |
1285 | /**
1286 | * Set a configuration for the context.
1287 | * @param {Object} cfg config object to integrate.
1288 | */
1289 | configure: function (cfg) {
1290 | //Make sure the baseUrl ends in a slash.
1291 | if (cfg.baseUrl) {
1292 | if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
1293 | cfg.baseUrl += '/';
1294 | }
1295 | }
1296 |
1297 | //Save off the paths and packages since they require special processing,
1298 | //they are additive.
1299 | var pkgs = config.pkgs,
1300 | shim = config.shim,
1301 | paths = config.paths,
1302 | map = config.map;
1303 |
1304 | //Mix in the config values, favoring the new values over
1305 | //existing ones in context.config.
1306 | mixin(config, cfg, true);
1307 |
1308 | //Merge paths.
1309 | config.paths = mixin(paths, cfg.paths, true);
1310 |
1311 | //Merge map
1312 | if (cfg.map) {
1313 | config.map = mixin(map || {}, cfg.map, true, true);
1314 | }
1315 |
1316 | //Merge shim
1317 | if (cfg.shim) {
1318 | eachProp(cfg.shim, function (value, id) {
1319 | //Normalize the structure
1320 | if (isArray(value)) {
1321 | value = {
1322 | deps: value
1323 | };
1324 | }
1325 | if (value.exports && !value.exports.__buildReady) {
1326 | value.exports = context.makeShimExports(value.exports);
1327 | }
1328 | shim[id] = value;
1329 | });
1330 | config.shim = shim;
1331 | }
1332 |
1333 | //Adjust packages if necessary.
1334 | if (cfg.packages) {
1335 | each(cfg.packages, function (pkgObj) {
1336 | var location;
1337 |
1338 | pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
1339 | location = pkgObj.location;
1340 |
1341 | //Create a brand new object on pkgs, since currentPackages can
1342 | //be passed in again, and config.pkgs is the internal transformed
1343 | //state for all package configs.
1344 | pkgs[pkgObj.name] = {
1345 | name: pkgObj.name,
1346 | location: location || pkgObj.name,
1347 | //Remove leading dot in main, so main paths are normalized,
1348 | //and remove any trailing .js, since different package
1349 | //envs have different conventions: some use a module name,
1350 | //some use a file name.
1351 | main: (pkgObj.main || 'main')
1352 | .replace(currDirRegExp, '')
1353 | .replace(jsSuffixRegExp, '')
1354 | };
1355 | });
1356 |
1357 | //Done with modifications, assing packages back to context config
1358 | config.pkgs = pkgs;
1359 | }
1360 |
1361 | //If there are any "waiting to execute" modules in the registry,
1362 | //update the maps for them, since their info, like URLs to load,
1363 | //may have changed.
1364 | eachProp(registry, function (mod, id) {
1365 | mod.map = makeModuleMap(id);
1366 | });
1367 |
1368 | //If a deps array or a config callback is specified, then call
1369 | //require with those args. This is useful when require is defined as a
1370 | //config object before require.js is loaded.
1371 | if (cfg.deps || cfg.callback) {
1372 | context.require(cfg.deps || [], cfg.callback);
1373 | }
1374 | },
1375 |
1376 | makeShimExports: function (exports) {
1377 | var func;
1378 | if (typeof exports === 'string') {
1379 | func = function () {
1380 | return getGlobal(exports);
1381 | };
1382 | //Save the exports for use in nodefine checking.
1383 | func.exports = exports;
1384 | return func;
1385 | } else {
1386 | return function () {
1387 | return exports.apply(global, arguments);
1388 | };
1389 | }
1390 | },
1391 |
1392 | requireDefined: function (id, relMap) {
1393 | return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
1394 | },
1395 |
1396 | requireSpecified: function (id, relMap) {
1397 | id = makeModuleMap(id, relMap, false, true).id;
1398 | return hasProp(defined, id) || hasProp(registry, id);
1399 | },
1400 |
1401 | require: function (deps, callback, errback, relMap) {
1402 | var moduleName, id, map, requireMod, args;
1403 | if (typeof deps === 'string') {
1404 | if (isFunction(callback)) {
1405 | //Invalid call
1406 | return onError(makeError('requireargs', 'Invalid require call'), errback);
1407 | }
1408 |
1409 | //Synchronous access to one module. If require.get is
1410 | //available (as in the Node adapter), prefer that.
1411 | //In this case deps is the moduleName and callback is
1412 | //the relMap
1413 | if (req.get) {
1414 | return req.get(context, deps, callback);
1415 | }
1416 |
1417 | //Just return the module wanted. In this scenario, the
1418 | //second arg (if passed) is just the relMap.
1419 | moduleName = deps;
1420 | relMap = callback;
1421 |
1422 | //Normalize module name, if it contains . or ..
1423 | map = makeModuleMap(moduleName, relMap, false, true);
1424 | id = map.id;
1425 |
1426 | if (!hasProp(defined, id)) {
1427 | return onError(makeError('notloaded', 'Module name "' +
1428 | id +
1429 | '" has not been loaded yet for context: ' +
1430 | contextName));
1431 | }
1432 | return defined[id];
1433 | }
1434 |
1435 | //Callback require. Normalize args. if callback or errback is
1436 | //not a function, it means it is a relMap. Test errback first.
1437 | if (errback && !isFunction(errback)) {
1438 | relMap = errback;
1439 | errback = undefined;
1440 | }
1441 | if (callback && !isFunction(callback)) {
1442 | relMap = callback;
1443 | callback = undefined;
1444 | }
1445 |
1446 | //Any defined modules in the global queue, intake them now.
1447 | takeGlobalQueue();
1448 |
1449 | //Make sure any remaining defQueue items get properly processed.
1450 | while (defQueue.length) {
1451 | args = defQueue.shift();
1452 | if (args[0] === null) {
1453 | return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
1454 | } else {
1455 | //args are id, deps, factory. Should be normalized by the
1456 | //define() function.
1457 | callGetModule(args);
1458 | }
1459 | }
1460 |
1461 | //Mark all the dependencies as needing to be loaded.
1462 | requireMod = getModule(makeModuleMap(null, relMap));
1463 |
1464 | requireMod.init(deps, callback, errback, {
1465 | enabled: true
1466 | });
1467 |
1468 | checkLoaded();
1469 |
1470 | return context.require;
1471 | },
1472 |
1473 | undef: function (id) {
1474 | var map = makeModuleMap(id, null, true),
1475 | mod = registry[id];
1476 |
1477 | delete defined[id];
1478 | delete urlFetched[map.url];
1479 | delete undefEvents[id];
1480 |
1481 | if (mod) {
1482 | //Hold on to listeners in case the
1483 | //module will be attempted to be reloaded
1484 | //using a different config.
1485 | if (mod.events.defined) {
1486 | undefEvents[id] = mod.events;
1487 | }
1488 |
1489 | removeWaiting(id);
1490 | }
1491 | },
1492 |
1493 | /**
1494 | * Called to enable a module if it is still in the registry
1495 | * awaiting enablement. parent module is passed in for context,
1496 | * used by the optimizer.
1497 | */
1498 | enable: function (depMap, parent) {
1499 | var mod = registry[depMap.id];
1500 | if (mod) {
1501 | getModule(depMap).enable();
1502 | }
1503 | },
1504 |
1505 | /**
1506 | * Internal method used by environment adapters to complete a load event.
1507 | * A load event could be a script load or just a load pass from a synchronous
1508 | * load call.
1509 | * @param {String} moduleName the name of the module to potentially complete.
1510 | */
1511 | completeLoad: function (moduleName) {
1512 | var shim = config.shim[moduleName] || {},
1513 | shExports = shim.exports && shim.exports.exports,
1514 | found, args, mod;
1515 |
1516 | takeGlobalQueue();
1517 |
1518 | while (defQueue.length) {
1519 | args = defQueue.shift();
1520 | if (args[0] === null) {
1521 | args[0] = moduleName;
1522 | //If already found an anonymous module and bound it
1523 | //to this name, then this is some other anon module
1524 | //waiting for its completeLoad to fire.
1525 | if (found) {
1526 | break;
1527 | }
1528 | found = true;
1529 | } else if (args[0] === moduleName) {
1530 | //Found matching define call for this script!
1531 | found = true;
1532 | }
1533 |
1534 | callGetModule(args);
1535 | }
1536 |
1537 | //Do this after the cycle of callGetModule in case the result
1538 | //of those calls/init calls changes the registry.
1539 | mod = registry[moduleName];
1540 |
1541 | if (!found &&
1542 | !defined[moduleName] &&
1543 | mod && !mod.inited) {
1544 | if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
1545 | if (hasPathFallback(moduleName)) {
1546 | return;
1547 | } else {
1548 | return onError(makeError('nodefine',
1549 | 'No define call for ' + moduleName,
1550 | null,
1551 | [moduleName]));
1552 | }
1553 | } else {
1554 | //A script that does not call define(), so just simulate
1555 | //the call for it.
1556 | callGetModule([moduleName, (shim.deps || []), shim.exports]);
1557 | }
1558 | }
1559 |
1560 | checkLoaded();
1561 | },
1562 |
1563 | /**
1564 | * Converts a module name + .extension into an URL path.
1565 | * *Requires* the use of a module name. It does not support using
1566 | * plain URLs like nameToUrl.
1567 | */
1568 | toUrl: function (moduleNamePlusExt, relModuleMap) {
1569 | var index = moduleNamePlusExt.lastIndexOf('.'),
1570 | ext = null;
1571 |
1572 | if (index !== -1) {
1573 | ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
1574 | moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
1575 | }
1576 |
1577 | return context.nameToUrl(normalize(moduleNamePlusExt, relModuleMap && relModuleMap.id, true),
1578 | ext);
1579 | },
1580 |
1581 | /**
1582 | * Converts a module name to a file path. Supports cases where
1583 | * moduleName may actually be just an URL.
1584 | * Note that it **does not** call normalize on the moduleName,
1585 | * it is assumed to have already been normalized. This is an
1586 | * internal API, not a public one. Use toUrl for the public API.
1587 | */
1588 | nameToUrl: function (moduleName, ext) {
1589 | var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
1590 | parentPath;
1591 |
1592 | //If a colon is in the URL, it indicates a protocol is used and it is just
1593 | //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
1594 | //or ends with .js, then assume the user meant to use an url and not a module id.
1595 | //The slash is important for protocol-less URLs as well as full paths.
1596 | if (req.jsExtRegExp.test(moduleName)) {
1597 | //Just a plain path, not module name lookup, so just return it.
1598 | //Add extension if it is included. This is a bit wonky, only non-.js things pass
1599 | //an extension, this method probably needs to be reworked.
1600 | url = moduleName + (ext || '');
1601 | } else {
1602 | //A module that needs to be converted to a path.
1603 | paths = config.paths;
1604 | pkgs = config.pkgs;
1605 |
1606 | syms = moduleName.split('/');
1607 | //For each module name segment, see if there is a path
1608 | //registered for it. Start with most specific name
1609 | //and work up from it.
1610 | for (i = syms.length; i > 0; i -= 1) {
1611 | parentModule = syms.slice(0, i).join('/');
1612 | pkg = pkgs[parentModule];
1613 | parentPath = paths[parentModule];
1614 | if (parentPath) {
1615 | //If an array, it means there are a few choices,
1616 | //Choose the one that is desired
1617 | if (isArray(parentPath)) {
1618 | parentPath = parentPath[0];
1619 | }
1620 | syms.splice(0, i, parentPath);
1621 | break;
1622 | } else if (pkg) {
1623 | //If module name is just the package name, then looking
1624 | //for the main module.
1625 | if (moduleName === pkg.name) {
1626 | pkgPath = pkg.location + '/' + pkg.main;
1627 | } else {
1628 | pkgPath = pkg.location;
1629 | }
1630 | syms.splice(0, i, pkgPath);
1631 | break;
1632 | }
1633 | }
1634 |
1635 | //Join the path parts together, then figure out if baseUrl is needed.
1636 | url = syms.join('/') + (ext || '.js');
1637 | url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
1638 | }
1639 |
1640 | return config.urlArgs ? url +
1641 | ((url.indexOf('?') === -1 ? '?' : '&') +
1642 | config.urlArgs) : url;
1643 | },
1644 |
1645 | //Delegates to req.load. Broken out as a separate function to
1646 | //allow overriding in the optimizer.
1647 | load: function (id, url) {
1648 | req.load(context, id, url);
1649 | },
1650 |
1651 | /**
1652 | * Executes a module callack function. Broken out as a separate function
1653 | * solely to allow the build system to sequence the files in the built
1654 | * layer in the right sequence.
1655 | *
1656 | * @private
1657 | */
1658 | execCb: function (name, callback, args, exports) {
1659 | return callback.apply(exports, args);
1660 | },
1661 |
1662 | /**
1663 | * callback for script loads, used to check status of loading.
1664 | *
1665 | * @param {Event} evt the event from the browser for the script
1666 | * that was loaded.
1667 | */
1668 | onScriptLoad: function (evt) {
1669 | //Using currentTarget instead of target for Firefox 2.0's sake. Not
1670 | //all old browsers will be supported, but this one was easy enough
1671 | //to support and still makes sense.
1672 | if (evt.type === 'load' ||
1673 | (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
1674 | //Reset interactive script so a script node is not held onto for
1675 | //to long.
1676 | interactiveScript = null;
1677 |
1678 | //Pull out the name of the module and the context.
1679 | var data = getScriptData(evt);
1680 | context.completeLoad(data.id);
1681 | }
1682 | },
1683 |
1684 | /**
1685 | * Callback for script errors.
1686 | */
1687 | onScriptError: function (evt) {
1688 | var data = getScriptData(evt);
1689 | if (!hasPathFallback(data.id)) {
1690 | return onError(makeError('scripterror', 'Script error', evt, [data.id]));
1691 | }
1692 | }
1693 | });
1694 | }
1695 |
1696 | /**
1697 | * Main entry point.
1698 | *
1699 | * If the only argument to require is a string, then the module that
1700 | * is represented by that string is fetched for the appropriate context.
1701 | *
1702 | * If the first argument is an array, then it will be treated as an array
1703 | * of dependency string names to fetch. An optional function callback can
1704 | * be specified to execute when all of those dependencies are available.
1705 | *
1706 | * Make a local req variable to help Caja compliance (it assumes things
1707 | * on a require that are not standardized), and to give a short
1708 | * name for minification/local scope use.
1709 | */
1710 | req = requirejs = function (deps, callback, errback, optional) {
1711 |
1712 | //Find the right context, use default
1713 | var contextName = defContextName,
1714 | context, config;
1715 |
1716 | // Determine if have config object in the call.
1717 | if (!isArray(deps) && typeof deps !== 'string') {
1718 | // deps is a config object
1719 | config = deps;
1720 | if (isArray(callback)) {
1721 | // Adjust args if there are dependencies
1722 | deps = callback;
1723 | callback = errback;
1724 | errback = optional;
1725 | } else {
1726 | deps = [];
1727 | }
1728 | }
1729 |
1730 | if (config && config.context) {
1731 | contextName = config.context;
1732 | }
1733 |
1734 | context = contexts[contextName];
1735 | if (!context) {
1736 | context = contexts[contextName] = req.s.newContext(contextName);
1737 | }
1738 |
1739 | if (config) {
1740 | context.configure(config);
1741 | }
1742 |
1743 | return context.require(deps, callback, errback);
1744 | };
1745 |
1746 | /**
1747 | * Support require.config() to make it easier to cooperate with other
1748 | * AMD loaders on globally agreed names.
1749 | */
1750 | req.config = function (config) {
1751 | return req(config);
1752 | };
1753 |
1754 | /**
1755 | * Export require as a global, but only if it does not already exist.
1756 | */
1757 | if (!require) {
1758 | require = req;
1759 | }
1760 |
1761 | req.version = version;
1762 |
1763 | //Used to filter out dependencies that are already paths.
1764 | req.jsExtRegExp = /^\/|:|\?|\.js$/;
1765 | req.isBrowser = isBrowser;
1766 | s = req.s = {
1767 | contexts: contexts,
1768 | newContext: newContext
1769 | };
1770 |
1771 | //Create default context.
1772 | req({});
1773 |
1774 | //Exports some context-sensitive methods on global require, using
1775 | //default context if no context specified.
1776 | addRequireMethods(req);
1777 |
1778 | if (isBrowser) {
1779 | head = s.head = document.getElementsByTagName('head')[0];
1780 | //If BASE tag is in play, using appendChild is a problem for IE6.
1781 | //When that browser dies, this can be removed. Details in this jQuery bug:
1782 | //http://dev.jquery.com/ticket/2709
1783 | baseElement = document.getElementsByTagName('base')[0];
1784 | if (baseElement) {
1785 | head = s.head = baseElement.parentNode;
1786 | }
1787 | }
1788 |
1789 | /**
1790 | * Any errors that require explicitly generates will be passed to this
1791 | * function. Intercept/override it if you want custom error handling.
1792 | * @param {Error} err the error object.
1793 | */
1794 | req.onError = function (err) {
1795 | throw err;
1796 | };
1797 |
1798 | /**
1799 | * Does the request to load a module for the browser case.
1800 | * Make this a separate function to allow other environments
1801 | * to override it.
1802 | *
1803 | * @param {Object} context the require context to find state.
1804 | * @param {String} moduleName the name of the module.
1805 | * @param {Object} url the URL to the module.
1806 | */
1807 | req.load = function (context, moduleName, url) {
1808 | var config = (context && context.config) || {},
1809 | node;
1810 | if (isBrowser) {
1811 | //In the browser so use a script tag
1812 | node = config.xhtml ?
1813 | document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
1814 | document.createElement('script');
1815 | node.type = config.scriptType || 'text/javascript';
1816 | node.charset = 'utf-8';
1817 | node.async = true;
1818 |
1819 | node.setAttribute('data-requirecontext', context.contextName);
1820 | node.setAttribute('data-requiremodule', moduleName);
1821 |
1822 | //Set up load listener. Test attachEvent first because IE9 has
1823 | //a subtle issue in its addEventListener and script onload firings
1824 | //that do not match the behavior of all other browsers with
1825 | //addEventListener support, which fire the onload event for a
1826 | //script right after the script execution. See:
1827 | //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
1828 | //UNFORTUNATELY Opera implements attachEvent but does not follow the script
1829 | //script execution mode.
1830 | if (node.attachEvent &&
1831 | //Check if node.attachEvent is artificially added by custom script or
1832 | //natively supported by browser
1833 | //read https://github.com/jrburke/requirejs/issues/187
1834 | //if we can NOT find [native code] then it must NOT natively supported.
1835 | //in IE8, node.attachEvent does not have toString()
1836 | //Note the test for "[native code" with no closing brace, see:
1837 | //https://github.com/jrburke/requirejs/issues/273
1838 | !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
1839 | !isOpera) {
1840 | //Probably IE. IE (at least 6-8) do not fire
1841 | //script onload right after executing the script, so
1842 | //we cannot tie the anonymous define call to a name.
1843 | //However, IE reports the script as being in 'interactive'
1844 | //readyState at the time of the define call.
1845 | useInteractive = true;
1846 |
1847 | node.attachEvent('onreadystatechange', context.onScriptLoad);
1848 | //It would be great to add an error handler here to catch
1849 | //404s in IE9+. However, onreadystatechange will fire before
1850 | //the error handler, so that does not help. If addEvenListener
1851 | //is used, then IE will fire error before load, but we cannot
1852 | //use that pathway given the connect.microsoft.com issue
1853 | //mentioned above about not doing the 'script execute,
1854 | //then fire the script load event listener before execute
1855 | //next script' that other browsers do.
1856 | //Best hope: IE10 fixes the issues,
1857 | //and then destroys all installs of IE 6-9.
1858 | //node.attachEvent('onerror', context.onScriptError);
1859 | } else {
1860 | node.addEventListener('load', context.onScriptLoad, false);
1861 | node.addEventListener('error', context.onScriptError, false);
1862 | }
1863 | node.src = url;
1864 |
1865 | //For some cache cases in IE 6-8, the script executes before the end
1866 | //of the appendChild execution, so to tie an anonymous define
1867 | //call to the module name (which is stored on the node), hold on
1868 | //to a reference to this node, but clear after the DOM insertion.
1869 | currentlyAddingScript = node;
1870 | if (baseElement) {
1871 | head.insertBefore(node, baseElement);
1872 | } else {
1873 | head.appendChild(node);
1874 | }
1875 | currentlyAddingScript = null;
1876 |
1877 | return node;
1878 | } else if (isWebWorker) {
1879 | //In a web worker, use importScripts. This is not a very
1880 | //efficient use of importScripts, importScripts will block until
1881 | //its script is downloaded and evaluated. However, if web workers
1882 | //are in play, the expectation that a build has been done so that
1883 | //only one script needs to be loaded anyway. This may need to be
1884 | //reevaluated if other use cases become common.
1885 | importScripts(url);
1886 |
1887 | //Account for anonymous modules
1888 | context.completeLoad(moduleName);
1889 | }
1890 | };
1891 |
1892 | function getInteractiveScript() {
1893 | if (interactiveScript && interactiveScript.readyState === 'interactive') {
1894 | return interactiveScript;
1895 | }
1896 |
1897 | eachReverse(scripts(), function (script) {
1898 | if (script.readyState === 'interactive') {
1899 | return (interactiveScript = script);
1900 | }
1901 | });
1902 | return interactiveScript;
1903 | }
1904 |
1905 | //Look for a data-main script attribute, which could also adjust the baseUrl.
1906 | if (isBrowser) {
1907 | //Figure out baseUrl. Get it from the script tag with require.js in it.
1908 | eachReverse(scripts(), function (script) {
1909 | //Set the 'head' where we can append children by
1910 | //using the script's parent.
1911 | if (!head) {
1912 | head = script.parentNode;
1913 | }
1914 |
1915 | //Look for a data-main attribute to set main script for the page
1916 | //to load. If it is there, the path to data main becomes the
1917 | //baseUrl, if it is not already set.
1918 | dataMain = script.getAttribute('data-main');
1919 | if (dataMain) {
1920 | //Set final baseUrl if there is not already an explicit one.
1921 | if (!cfg.baseUrl) {
1922 | //Pull off the directory of data-main for use as the
1923 | //baseUrl.
1924 | src = dataMain.split('/');
1925 | mainScript = src.pop();
1926 | subPath = src.length ? src.join('/') + '/' : './';
1927 |
1928 | cfg.baseUrl = subPath;
1929 | dataMain = mainScript;
1930 | }
1931 |
1932 | //Strip off any trailing .js since dataMain is now
1933 | //like a module name.
1934 | dataMain = dataMain.replace(jsSuffixRegExp, '');
1935 |
1936 | //Put the data-main script in the files to load.
1937 | cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
1938 |
1939 | return true;
1940 | }
1941 | });
1942 | }
1943 |
1944 | /**
1945 | * The function that handles definitions of modules. Differs from
1946 | * require() in that a string for the module should be the first argument,
1947 | * and the function to execute after dependencies are loaded should
1948 | * return a value to define the module corresponding to the first argument's
1949 | * name.
1950 | */
1951 | define = function (name, deps, callback) {
1952 | var node, context;
1953 |
1954 | //Allow for anonymous functions
1955 | if (typeof name !== 'string') {
1956 | //Adjust args appropriately
1957 | callback = deps;
1958 | deps = name;
1959 | name = null;
1960 | }
1961 |
1962 | //This module may not have dependencies
1963 | if (!isArray(deps)) {
1964 | callback = deps;
1965 | deps = [];
1966 | }
1967 |
1968 | //If no name, and callback is a function, then figure out if it a
1969 | //CommonJS thing with dependencies.
1970 | if (!deps.length && isFunction(callback)) {
1971 | //Remove comments from the callback string,
1972 | //look for require calls, and pull them into the dependencies,
1973 | //but only if there are function args.
1974 | if (callback.length) {
1975 | callback
1976 | .toString()
1977 | .replace(commentRegExp, '')
1978 | .replace(cjsRequireRegExp, function (match, dep) {
1979 | deps.push(dep);
1980 | });
1981 |
1982 | //May be a CommonJS thing even without require calls, but still
1983 | //could use exports, and module. Avoid doing exports and module
1984 | //work though if it just needs require.
1985 | //REQUIRES the function to expect the CommonJS variables in the
1986 | //order listed below.
1987 | deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
1988 | }
1989 | }
1990 |
1991 | //If in IE 6-8 and hit an anonymous define() call, do the interactive
1992 | //work.
1993 | if (useInteractive) {
1994 | node = currentlyAddingScript || getInteractiveScript();
1995 | if (node) {
1996 | if (!name) {
1997 | name = node.getAttribute('data-requiremodule');
1998 | }
1999 | context = contexts[node.getAttribute('data-requirecontext')];
2000 | }
2001 | }
2002 |
2003 | //Always save off evaluating the def call until the script onload handler.
2004 | //This allows multiple modules to be in a file without prematurely
2005 | //tracing dependencies, and allows for anonymous module support,
2006 | //where the module name is not known until the script onload event
2007 | //occurs. If no context, use the global queue, and get it processed
2008 | //in the onscript load callback.
2009 | (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
2010 | };
2011 |
2012 | define.amd = {
2013 | jQuery: true
2014 | };
2015 |
2016 |
2017 | /**
2018 | * Executes the text. Normally just uses eval, but can be modified
2019 | * to use a better, environment-specific call. Only used for transpiling
2020 | * loader plugins, not for plain JS modules.
2021 | * @param {String} text the text to execute/evaluate.
2022 | */
2023 | req.exec = function (text) {
2024 | /*jslint evil: true */
2025 | return eval(text);
2026 | };
2027 |
2028 | //Set up with config info.
2029 | req(cfg);
2030 | }(this));
2031 |
--------------------------------------------------------------------------------