Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added readme, and replace files so that repo is a template game inste…

…ad of just the library files.
  • Loading branch information...
commit 3ba56ba610f461537dd365073dbc90538c8c60e7 1 parent 488b32c
Michael Kelly authored
View
14 COPYING
@@ -0,0 +1,14 @@
+Badly Designed Game Engine
+Copyright (c) 2010, Michael Kelly <Osmose1000@gmail.com>
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
View
19 index.html
@@ -0,0 +1,19 @@
+<html>
+<head>
+ <title>BDGE</title>
+ <link rel="stylesheet" type="text/css" href="reset-min.css">
+ <style type="text/css" media="screen">
+ html, body {
+ background: #000000;
+ }
+
+ * {
+ image-rendering: -moz-crisp-edges;
+ }
+ </style>
+</head>
+<body>
+<div id="main" tabindex="0"></div>
+</body>
+<script data-main="main" src="scripts/require.js"></script>
+</html>
View
9 readme.markdown
@@ -0,0 +1,9 @@
+Badly Designed Game Engine
+--------------------------
+BDGE is a game engine written in Javascript that uses HTML5 Canvas and Audio to create in-browser games.
+
+How Do I Create a Game?
+=======================
+1. Clone this repo to a new directory (like `my_game`)
+2. Edit `my_game/scripts/main.js` to add your game code
+3. View `my_game/index.html` to play your game
View
8 reset-min.css
@@ -0,0 +1,8 @@
+/*
+Copyright (c) 2010, Yahoo! Inc. All rights reserved.
+Code licensed under the BSD License:
+http://developer.yahoo.com/yui/license.html
+version: 3.2.0
+build: 2676
+*/
+html{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,textarea,p,blockquote,th,td{margin:0;padding:0;}table{border-collapse:collapse;border-spacing:0;}fieldset,img{border:0;}address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}li{list-style:none;}caption,th{text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;font-weight:normal;}q:before,q:after{content:'';}abbr,acronym{border:0;font-variant:normal;}sup{vertical-align:text-top;}sub{vertical-align:text-bottom;}input,textarea,select{font-family:inherit;font-size:inherit;font-weight:inherit;}input,textarea,select{*font-size:100%;}legend{color:#000;}
View
0  audio.js → scripts/bdge/audio.js
File renamed without changes
View
0  bdge.js → scripts/bdge/bdge.js
File renamed without changes
View
0  draw.js → scripts/bdge/draw.js
File renamed without changes
View
0  engine.js → scripts/bdge/engine.js
File renamed without changes
View
0  extra/tilemap.js → scripts/bdge/extra/tilemap.js
File renamed without changes
View
0  input.js → scripts/bdge/input.js
File renamed without changes
View
0  loader.js → scripts/bdge/loader.js
File renamed without changes
View
0  util.js → scripts/bdge/util.js
File renamed without changes
View
23 scripts/main.js
@@ -0,0 +1,23 @@
+require(["bdge/bdge"], function(bdge) {
+
+// The function passed to setGameInit will be run before the engine starts
+// Most of your game logic will go inside this function
+bdge.setGameInit(function() {
+ // In order to access the engine, we require its components
+ var engine = require("bdge/engine");
+ var input = require("bdge/input");
+ var loader = require("bdge/loader");
+ var util = require("bdge/util");
+ var draw = require("bdge/draw");
+
+ // Define your game code
+});
+
+/*
+ * Now we start the loader, which in turn loads all of our resources and starts
+ * the engine. If a function is passed to start, it is run after the resources
+ * are loaded, before the first engine cycle.
+ */
+bdge.start();
+
+});
View
1,612 scripts/require.js
@@ -0,0 +1,1612 @@
+/** vim: et:ts=4:sw=4:sts=4
+ * @license RequireJS 0.2.1 Copyright (c) 2010, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+/*jslint white: false, plusplus: false */
+/*global window: false, navigator: false, document: false, importScripts: false,
+ jQuery: false, clearInterval: false, setInterval: false, self: false,
+ setTimeout: false */
+
+
+var require, define;
+(function () {
+ //Change this version number for each release.
+ var version = "0.2.1",
+ commentRegExp = /(\/\*([\s\S]*?)\*\/|\/\/(.*)$)/mg,
+ cjsRequireRegExp = /require\(["']([\w\!\-_\.\/]+)["']\)/g,
+ ostring = Object.prototype.toString,
+ ap = Array.prototype,
+ aps = ap.slice,
+ apsp = ap.splice,
+ isBrowser = !!(typeof window !== "undefined" && navigator && document),
+ isWebWorker = !isBrowser && typeof importScripts !== "undefined",
+ //PS3 indicates loaded and complete, but need to wait for complete
+ //specifically. Sequence is "loading", "loaded", execution,
+ // then "complete". The UA check is unfortunate, but not sure how
+ //to feature test w/o causing perf issues.
+ readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
+ /^complete$/ : /^(complete|loaded)$/,
+ defContextName = "_",
+ reqWaitIdPrefix = "_r@@",
+ empty = {},
+ contexts = {},
+ globalDefQueue = [],
+ interactiveScript = null,
+ isDone = false,
+ useInteractive = false,
+ //Default plugins that have remapped names, if no mapping
+ //already exists.
+ requirePlugins = {
+ "text": "require/text",
+ "i18n": "require/i18n",
+ "order": "require/order"
+ },
+ req, cfg = {}, currentlyAddingScript, s, head, baseElement, scripts, script,
+ rePkg, src, m, dataMain, i, scrollIntervalId, setReadyState;
+
+ function isFunction(it) {
+ return ostring.call(it) === "[object Function]";
+ }
+
+ function isArray(it) {
+ return ostring.call(it) === "[object Array]";
+ }
+
+ /**
+ * Simple function to mix in properties from source into target,
+ * but only if target does not already have a property of the same name.
+ * This is not robust in IE for transferring methods that match
+ * Object.prototype names, but the uses of mixin here seem unlikely to
+ * trigger a problem related to that.
+ */
+ function mixin(target, source, force) {
+ for (var prop in source) {
+ if (!(prop in empty) && (!(prop in target) || force)) {
+ target[prop] = source[prop];
+ }
+ }
+ return req;
+ }
+
+ /**
+ * Used to set up package paths from a packagePaths or packages config object.
+ * @param {Object} packages the object to store the new package config
+ * @param {Array} currentPackages an array of packages to configure
+ * @param {String} [dir] a prefix dir to use.
+ */
+ function configurePackageDir(packages, currentPackages, dir) {
+ var i, location, pkgObj;
+ for (i = 0; (pkgObj = currentPackages[i]); i++) {
+ pkgObj = typeof pkgObj === "string" ? { name: pkgObj } : pkgObj;
+ location = pkgObj.location;
+
+ //Add dir to the path, but avoid paths that start with a slash
+ //or have a colon (indicates a protocol)
+ if (dir && (!location || (location.indexOf("/") !== 0 && location.indexOf(":") === -1))) {
+ pkgObj.location = dir + "/" + (pkgObj.location || pkgObj.name);
+ }
+
+ //Normalize package paths.
+ pkgObj.location = pkgObj.location || pkgObj.name;
+ pkgObj.lib = pkgObj.lib || "lib";
+ pkgObj.main = pkgObj.main || "main";
+
+ packages[pkgObj.name] = pkgObj;
+ }
+ }
+
+ //Check for an existing version of require. If so, then exit out. Only allow
+ //one version of require to be active in a page. However, allow for a require
+ //config object, just exit quickly if require is an actual function.
+ if (typeof require !== "undefined") {
+ if (isFunction(require)) {
+ return;
+ } else {
+ //assume it is a config object.
+ cfg = require;
+ }
+ }
+
+ /**
+ * Creates a new context for use in require and define calls.
+ * Handle most of the heavy lifting. Do not want to use an object
+ * with prototype here to avoid using "this" in require, in case it
+ * needs to be used in more super secure envs that do not want this.
+ * Also there should not be that many contexts in the page. Usually just
+ * one for the default context, but could be extra for multiversion cases
+ * or if a package needs a special context for a dependency that conflicts
+ * with the standard context.
+ */
+ function newContext(contextName) {
+ var context, resume,
+ config = {
+ waitSeconds: 7,
+ baseUrl: s.baseUrl || "./",
+ paths: {},
+ packages: {}
+ },
+ defQueue = [],
+ specified = {
+ "require": true,
+ "exports": true,
+ "module": true
+ },
+ defined = {},
+ loaded = {},
+ waiting = {},
+ waitAry = [],
+ waitIdCounter = 0,
+ managerCallbacks = {},
+ plugins = {},
+ pluginsQueue = {};
+
+ /**
+ * Given a relative module name, like ./something, normalize it to
+ * a real name that can be mapped to a path.
+ * @param {String} name the relative name
+ * @param {String} baseName a real name that the name arg is relative
+ * to.
+ * @returns {String} normalized name
+ */
+ function normalizeName(name, baseName) {
+ //Adjust any relative paths.
+ var part, i;
+ if (name.charAt(0) === ".") {
+ //If have a base name, try to normalize against it,
+ //otherwise, assume it is a top-level require that will
+ //be relative to baseUrl in the end.
+ if (baseName) {
+ if (context.config.packages[baseName]) {
+ //If the baseName is a package name, then just treat it as one
+ //name to concat the name with.
+ baseName = [baseName];
+ } else {
+ //Convert baseName to array, and lop off the last part,
+ //so that . matches that "directory" and not name of the baseName's
+ //module. For instance, baseName of "one/two/three", maps to
+ //"one/two/three.js", but we want the directory, "one/two" for
+ //this normalization.
+ baseName = baseName.split("/");
+ baseName = baseName.slice(0, baseName.length - 1);
+ }
+
+ name = baseName.concat(name.split("/"));
+ for (i = 0; (part = name[i]); i++) {
+ if (part === ".") {
+ name.splice(i, 1);
+ i -= 1;
+ } else if (part === "..") {
+ if (i === 1) {
+ //End of the line. Keep at least one non-dot
+ //path segment at the front so it can be mapped
+ //correctly to disk. Otherwise, there is likely
+ //no path mapping for '..'.
+ break;
+ } else if (i > 1) {
+ name.splice(i - 1, 2);
+ i -= 2;
+ }
+ }
+ }
+ name = name.join("/");
+ }
+ }
+ return name;
+ }
+
+ /**
+ * Splits a name into a possible plugin prefix and
+ * the module name. If baseName is provided it will
+ * also normalize the name via require.normalizeName()
+ *
+ * @param {String} name the module name
+ * @param {String} [baseName] base name that name is
+ * relative to.
+ *
+ * @returns {Object} with properties, 'prefix' (which
+ * may be null), 'name' and 'fullName', which is a combination
+ * of the prefix (if it exists) and the name.
+ */
+ function splitPrefix(name, baseName) {
+ var index = name ? name.indexOf("!") : -1, prefix = null;
+ if (index !== -1) {
+ prefix = name.substring(0, index);
+ name = name.substring(index + 1, name.length);
+ }
+
+ //Account for relative paths if there is a base name.
+ if (name) {
+ name = normalizeName(name, baseName);
+ }
+ if (prefix) {
+ prefix = normalizeName(prefix, baseName);
+ //Allow simpler mappings for some plugins
+ prefix = requirePlugins[prefix] || prefix;
+ }
+
+ return {
+ prefix: prefix,
+ name: name,
+ parentName: baseName,
+ fullName: prefix ? prefix + "!" + name : name
+ };
+ }
+
+ /**
+ * Determine if priority loading is done. If so clear the priorityWait
+ */
+ function isPriorityDone() {
+ var priorityDone = true,
+ priorityWait = config.priorityWait,
+ priorityName, i;
+ if (priorityWait) {
+ for (i = 0; (priorityName = priorityWait[i]); i++) {
+ if (!loaded[priorityName]) {
+ priorityDone = false;
+ break;
+ }
+ }
+ if (priorityDone) {
+ delete config.priorityWait;
+ }
+ }
+ return priorityDone;
+ }
+
+ /**
+ * As of jQuery 1.4.3, it supports a readyWait property that will hold off
+ * calling jQuery ready callbacks until all scripts are loaded. Be sure
+ * to track it if readyWait is available. Also, since jQuery 1.4.3 does
+ * not register as a module, need to do some global inference checking.
+ * Even if it does register as a module, not guaranteed to be the precise
+ * name of the global. If a jQuery is tracked for this context, then go
+ * ahead and register it as a module too, if not already in process.
+ */
+ function jQueryCheck(jqCandidate) {
+ if (!context.jQuery) {
+ var $ = jqCandidate || (typeof jQuery !== "undefined" ? jQuery : null);
+ if ($ && "readyWait" in $) {
+ context.jQuery = $;
+
+ //Manually create a "jquery" module entry if not one already
+ //or in process.
+ if (!defined.jquery && !context.jQueryDef) {
+ defined.jquery = $;
+ }
+
+ //Increment jQuery readyWait if ncecessary.
+ if (context.scriptCount) {
+ $.readyWait += 1;
+ context.jQueryIncremented = true;
+ }
+ }
+ }
+ }
+
+ /**
+ * Helper function that creates a setExports function for a "module"
+ * CommonJS dependency. Do this here to avoid creating a closure that
+ * is part of a loop.
+ */
+ function makeSetExports(moduleObj) {
+ return function (exports) {
+ moduleObj.exports = exports;
+ };
+ }
+
+ function makeContextModuleFunc(func, moduleName) {
+ return function () {
+ //A version of a require function that passes a moduleName
+ //value for items that may need to
+ //look up paths relative to the moduleName
+ var args = [].concat(aps.call(arguments, 0));
+ args.push(moduleName);
+ return func.apply(null, args);
+ };
+ }
+
+ /**
+ * Helper function that creates a require function object to give to
+ * modules that ask for it as a dependency. It needs to be specific
+ * per module because of the implication of path mappings that may
+ * need to be relative to the module name.
+ */
+ function makeRequire(moduleName) {
+ var modRequire = makeContextModuleFunc(context.require, moduleName);
+
+ mixin(modRequire, {
+ nameToUrl: makeContextModuleFunc(context.nameToUrl, moduleName),
+ toUrl: makeContextModuleFunc(context.toUrl, moduleName),
+ isDefined: makeContextModuleFunc(context.isDefined, moduleName),
+ ready: req.ready,
+ isBrowser: req.isBrowser
+ });
+ return modRequire;
+ }
+
+ /*
+ * Queues a dependency for checking after the loader is out of a
+ * "paused" state, for example while a script file is being loaded
+ * in the browser, where it may have many modules defined in it.
+ *
+ * depName will be fully qualified, no relative . or .. path.
+ */
+ function queueDependency(dep) {
+ //Make sure to load any plugin and associate the dependency
+ //with that plugin.
+ var prefix = dep.prefix,
+ fullName = dep.fullName;
+
+ //Do not bother if the depName is already in transit
+ if (specified[fullName] || fullName in defined) {
+ return;
+ }
+
+ if (prefix) {
+ //Queue up loading of the dependency, track it
+ //via context.plugins
+ context.plugins[prefix] = undefined;
+ queueDependency(splitPrefix(prefix));
+ }
+
+ context.paused.push(dep);
+ }
+
+ function execManager(manager) {
+ var i, ret, waitingCallbacks,
+ cb = manager.callback,
+ fullName = manager.fullName,
+ args = [],
+ ary = manager.depArray;
+
+ //Call the callback to define the module, if necessary.
+ if (cb && isFunction(cb)) {
+ //Pull out the defined dependencies and pass the ordered
+ //values to the callback.
+ if (ary) {
+ for (i = 0; i < ary.length; i++) {
+ args.push(manager.deps[ary[i]]);
+ }
+ }
+
+ ret = req.execCb(fullName, manager.callback, args);
+
+ if (fullName) {
+ //If using exports and the function did not return a value,
+ //and the "module" object for this definition function did not
+ //define an exported value, then use the exports object.
+ if (manager.usingExports && ret === undefined && (!manager.cjsModule || !("exports" in manager.cjsModule))) {
+ ret = defined[fullName];
+ } else {
+ if (manager.cjsModule && "exports" in manager.cjsModule) {
+ ret = defined[fullName] = manager.cjsModule.exports;
+ } else {
+ if (fullName in defined && !manager.usingExports) {
+ return req.onError(new Error(fullName + " has already been defined"));
+ }
+ defined[fullName] = ret;
+ }
+ }
+ }
+ } else if (fullName) {
+ //May just be an object definition for the module. Only
+ //worry about defining if have a module name.
+ ret = defined[fullName] = cb;
+ }
+
+ if (fullName) {
+ //If anything was waiting for this module to be defined,
+ //notify them now.
+ waitingCallbacks = managerCallbacks[fullName];
+ if (waitingCallbacks) {
+ for (i = 0; i < waitingCallbacks.length; i++) {
+ waitingCallbacks[i].onDep(fullName, ret);
+ }
+ delete managerCallbacks[fullName];
+ }
+ }
+
+ //Clean up waiting.
+ if (waiting[manager.waitId]) {
+ delete waiting[manager.waitId];
+ manager.isDone = true;
+ context.waitCount -= 1;
+ if (context.waitCount === 0) {
+ //Clear the wait array used for cycles.
+ waitAry = [];
+ }
+ }
+
+ return undefined;
+ }
+
+ function main(inName, depArray, callback, relModuleName) {
+ var nameArgs = splitPrefix(inName, relModuleName),
+ name = nameArgs.name,
+ fullName = nameArgs.fullName,
+ manager = {
+ //Use a wait ID because some entries are anon
+ //async require calls.
+ waitId: name || reqWaitIdPrefix + (waitIdCounter++),
+ depCount: 0,
+ depMax: 0,
+ prefix: nameArgs.prefix,
+ name: name,
+ fullName: fullName,
+ deps: {},
+ depArray: depArray,
+ callback: callback,
+ onDep: function (depName, value) {
+ if (!(depName in manager.deps)) {
+ manager.deps[depName] = value;
+ manager.depCount += 1;
+ if (manager.depCount === manager.depMax) {
+ //All done, execute!
+ execManager(manager);
+ }
+ }
+ }
+ },
+ i, depArg, depName, cjsMod;
+
+ if (fullName) {
+ //If module already defined for context, or already loaded,
+ //then leave.
+ if (fullName in defined || loaded[fullName] === true) {
+ return;
+ }
+
+ //Set specified/loaded here for modules that are also loaded
+ //as part of a layer, where onScriptLoad is not fired
+ //for those cases. Do this after the inline define and
+ //dependency tracing is done.
+ //Also check if auto-registry of jQuery needs to be skipped.
+ specified[fullName] = true;
+ loaded[fullName] = true;
+ context.jQueryDef = (fullName === "jquery");
+ }
+
+ //Add the dependencies to the deps field, and register for callbacks
+ //on the dependencies.
+ for (i = 0; i < depArray.length; i++) {
+ depArg = depArray[i];
+ //There could be cases like in IE, where a trailing comma will
+ //introduce a null dependency, so only treat a real dependency
+ //value as a dependency.
+ if (depArg) {
+ //Split the dependency name into plugin and name parts
+ depArg = splitPrefix(depArg, (name || relModuleName));
+ depName = depArg.fullName;
+
+ //Fix the name in depArray to be just the name, since
+ //that is how it will be called back later.
+ depArray[i] = depName;
+
+ //Fast path CommonJS standard dependencies.
+ if (depName === "require") {
+ manager.deps[depName] = makeRequire(name);
+ } else if (depName === "exports") {
+ //CommonJS module spec 1.1
+ manager.deps[depName] = defined[fullName] = {};
+ manager.usingExports = true;
+ } else if (depName === "module") {
+ //CommonJS module spec 1.1
+ manager.cjsModule = cjsMod = manager.deps[depName] = {
+ id: name,
+ uri: name ? context.nameToUrl(name, null, relModuleName) : undefined
+ };
+ cjsMod.setExports = makeSetExports(cjsMod);
+ } else if (depName in defined && !(depName in waiting)) {
+ //Module already defined, no need to wait for it.
+ manager.deps[depName] = defined[depName];
+ } else {
+ //A dynamic dependency.
+ manager.depMax += 1;
+
+ queueDependency(depArg);
+
+ //Register to get notification when dependency loads.
+ (managerCallbacks[depName] ||
+ (managerCallbacks[depName] = [])).push(manager);
+ }
+ }
+ }
+
+ //Do not bother tracking the manager if it is all done.
+ if (manager.depCount === manager.depMax) {
+ //All done, execute!
+ execManager(manager);
+ } else {
+ waiting[manager.waitId] = manager;
+ waitAry.push(manager);
+ context.waitCount += 1;
+ }
+ }
+
+ /**
+ * Convenience method to call main for a require.def call that was put on
+ * hold in the defQueue.
+ */
+ function callDefMain(args) {
+ main.apply(null, args);
+ //Mark the module loaded. Must do it here in addition
+ //to doing it in require.def in case a script does
+ //not call require.def
+ loaded[args[0]] = true;
+ }
+
+ function forceExec(manager, traced) {
+ if (manager.isDone) {
+ return undefined;
+ }
+
+ var fullName = manager.fullName,
+ depArray = manager.depArray,
+ depName, i;
+ if (fullName) {
+ if (traced[fullName]) {
+ return defined[fullName];
+ }
+
+ traced[fullName] = true;
+ }
+
+ //forceExec all of its dependencies.
+ for (i = 0; i < depArray.length; i++) {
+ //Some array members may be null, like if a trailing comma
+ //IE, so do the explicit [i] access and check if it has a value.
+ depName = depArray[i];
+ if (depName) {
+ if (!manager.deps[depName] && waiting[depName]) {
+ manager.onDep(depName, forceExec(waiting[depName], traced));
+ }
+ }
+ }
+
+ return fullName ? defined[fullName] : undefined;
+ }
+
+ /**
+ * Checks if all modules for a context are loaded, and if so, evaluates the
+ * new ones in right dependency order.
+ *
+ * @private
+ */
+ function checkLoaded() {
+ var waitInterval = config.waitSeconds * 1000,
+ //It is possible to disable the wait interval by using waitSeconds of 0.
+ expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
+ noLoads = "", hasLoadedProp = false, stillLoading = false, prop,
+ err, manager;
+
+ //Determine if priority loading is done. If so clear the priority. If
+ //not, then do not check
+ if (config.priorityWait) {
+ if (isPriorityDone()) {
+ //Call resume, since it could have
+ //some waiting dependencies to trace.
+ resume();
+ } else {
+ return undefined;
+ }
+ }
+
+ //See if anything is still in flight.
+ for (prop in loaded) {
+ if (!(prop in empty)) {
+ hasLoadedProp = true;
+ if (!loaded[prop]) {
+ if (expired) {
+ noLoads += prop + " ";
+ } else {
+ stillLoading = true;
+ break;
+ }
+ }
+ }
+ }
+
+ //Check for exit conditions.
+ if (!hasLoadedProp && !context.waitCount) {
+ //If the loaded object had no items, then the rest of
+ //the work below does not need to be done.
+ return undefined;
+ }
+ if (expired && noLoads) {
+ //If wait time expired, throw error of unloaded modules.
+ err = new Error("require.js load timeout for modules: " + noLoads);
+ err.requireType = "timeout";
+ err.requireModules = noLoads;
+ return req.onError(err);
+ }
+ if (stillLoading || context.scriptCount) {
+ //Something is still waiting to load. Wait for it.
+ if (isBrowser || isWebWorker) {
+ setTimeout(checkLoaded, 50);
+ }
+ return undefined;
+ }
+
+ //If still have items in the waiting cue, but all modules have
+ //been loaded, then it means there are some circular dependencies
+ //that need to be broken.
+ //However, as a waiting thing is fired, then it can add items to
+ //the waiting cue, and those items should not be fired yet, so
+ //make sure to redo the checkLoaded call after breaking a single
+ //cycle, if nothing else loaded then this logic will pick it up
+ //again.
+ if (context.waitCount) {
+ //Cycle through the waitAry, and call items in sequence.
+ for (i = 0; (manager = waitAry[i]); i++) {
+ forceExec(manager, {});
+ }
+
+ checkLoaded();
+ return undefined;
+ }
+
+ //Check for DOM ready, and nothing is waiting across contexts.
+ req.checkReadyState();
+
+ return undefined;
+ }
+
+ function callPlugin(pluginName, dep) {
+ var name = dep.name,
+ fullName = dep.fullName;
+
+ //Do not bother if plugin is already defined.
+ if (fullName in defined) {
+ return;
+ }
+
+ if (!plugins[pluginName]) {
+ plugins[pluginName] = defined[pluginName];
+ }
+
+ //Only set loaded to false for tracking if it has not already been set.
+ if (!loaded[fullName]) {
+ loaded[fullName] = false;
+ }
+
+ //Use parentName here since the plugin's name is not reliable,
+ //could be some weird string with no path that actually wants to
+ //reference the parentName's path.
+ plugins[pluginName].load(name, makeRequire(dep.parentName), function (ret) {
+ //Allow the build process to register plugin-loaded dependencies.
+ if (require.onPluginLoad) {
+ require.onPluginLoad(context, pluginName, name, ret);
+ }
+
+ execManager({
+ prefix: dep.prefix,
+ name: dep.name,
+ fullName: dep.fullName,
+ callback: ret
+ });
+ loaded[fullName] = true;
+ }, config);
+ }
+
+ function loadPaused(dep) {
+ var pluginName = dep.prefix,
+ fullName = dep.fullName;
+
+ //Do not bother if the dependency has already been specified.
+ if (specified[fullName] || fullName in defined) {
+ return;
+ } else {
+ specified[fullName] = true;
+ }
+
+ if (pluginName) {
+ //If plugin not loaded, wait for it.
+ //set up callback list. if no list, then register
+ //managerCallback for that plugin.
+ if (defined[pluginName]) {
+ callPlugin(pluginName, dep);
+ } else {
+ if (!pluginsQueue[pluginName]) {
+ pluginsQueue[pluginName] = [];
+ (managerCallbacks[pluginName] ||
+ (managerCallbacks[pluginName] = [])).push({
+ onDep: function (name, value) {
+ if (name === pluginName) {
+ var i, ary = pluginsQueue[pluginName];
+ for (i = 0; i < ary.length; i++) {
+ callPlugin(pluginName, ary[i]);
+ }
+ delete pluginsQueue[pluginName];
+ }
+ }
+ });
+ }
+ pluginsQueue[pluginName].push(dep);
+ }
+ } else {
+ req.load(context, fullName);
+ }
+ }
+
+ /**
+ * Resumes tracing of dependencies and then checks if everything is loaded.
+ */
+ resume = function () {
+ var args, i, p;
+
+ if (context.scriptCount <= 0) {
+ //Synchronous envs will push the number below zero with the
+ //decrement above, be sure to set it back to zero for good measure.
+ //require() calls that also do not end up loading scripts could
+ //push the number negative too.
+ context.scriptCount = 0;
+ }
+
+ //Make sure any remaining defQueue items get properly processed.
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ return req.onError(new Error('Mismatched anonymous require.def modules'));
+ } else {
+ callDefMain(args);
+ }
+ }
+
+ //Skip the resume if current context is in priority wait.
+ if (config.priorityWait && !isPriorityDone()) {
+ return undefined;
+ }
+
+ while (context.paused.length) {
+ p = context.paused;
+ //Reset paused list
+ context.paused = [];
+
+ for (i = 0; (args = p[i]); i++) {
+ loadPaused(args);
+ }
+ //Move the start time for timeout forward.
+ context.startTime = (new Date()).getTime();
+ }
+
+ checkLoaded();
+
+ return undefined;
+ };
+
+ //Define the context object. Many of these fields are on here
+ //just to make debugging easier.
+ context = {
+ contextName: contextName,
+ config: config,
+ defQueue: defQueue,
+ waiting: waiting,
+ waitCount: 0,
+ specified: specified,
+ loaded: loaded,
+ scriptCount: 0,
+ urlFetched: {},
+ defined: defined,
+ paused: [],
+ plugins: plugins,
+ managerCallbacks: managerCallbacks,
+ splitPrefix: splitPrefix,
+ normalizeName: normalizeName,
+ /**
+ * Set a configuration for the context.
+ * @param {Object} cfg config object to integrate.
+ */
+ configure: function (cfg) {
+ var paths, packages, prop, packagePaths;
+
+ //Make sure the baseUrl ends in a slash.
+ if (cfg.baseUrl) {
+ if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== "/") {
+ cfg.baseUrl += "/";
+ }
+ }
+
+ //Save off the paths and packages since they require special processing,
+ //they are additive.
+ paths = config.paths;
+ packages = config.packages;
+
+ //Mix in the config values, favoring the new values over
+ //existing ones in context.config.
+ mixin(config, cfg, true);
+
+ //Adjust paths if necessary.
+ if (cfg.paths) {
+ for (prop in cfg.paths) {
+ if (!(prop in empty)) {
+ paths[prop] = cfg.paths[prop];
+ }
+ }
+ config.paths = paths;
+ }
+
+ packagePaths = cfg.packagePaths;
+ if (packagePaths || cfg.packages) {
+ //Convert packagePaths into a packages config.
+ if (packagePaths) {
+ for (prop in packagePaths) {
+ if (!(prop in empty)) {
+ configurePackageDir(packages, packagePaths[prop], prop);
+ }
+ }
+ }
+
+ //Adjust packages if necessary.
+ if (cfg.packages) {
+ configurePackageDir(packages, cfg.packages);
+ }
+
+ //Done with modifications, assing packages back to context config
+ config.packages = packages;
+ }
+
+ //If priority loading is in effect, trigger the loads now
+ if (cfg.priority) {
+ //Create a separate config property that can be
+ //easily tested for config priority completion.
+ //Do this instead of wiping out the config.priority
+ //in case it needs to be inspected for debug purposes later.
+ context.require(cfg.priority);
+ config.priorityWait = cfg.priority;
+ }
+
+ //If a deps array or a config callback is specified, then call
+ //require with those args. This is useful when require is defined as a
+ //config object before require.js is loaded.
+ if (cfg.deps || cfg.callback) {
+ context.require(cfg.deps || [], cfg.callback);
+ }
+
+ //Set up ready callback, if asked. Useful when require is defined as a
+ //config object before require.js is loaded.
+ if (cfg.ready) {
+ req.ready(cfg.ready);
+ }
+ },
+
+ isDefined: function (moduleName, relModuleName) {
+ return splitPrefix(moduleName, relModuleName).fullName in defined;
+ },
+
+ require: function (deps, callback, relModuleName) {
+ var moduleName, ret, nameProps;
+ if (typeof deps === "string") {
+ //Synchronous access to one module. If require.get is
+ //available (as in the Node adapter), prefer that.
+ //In this case deps is the moduleName and callback is
+ //the relModuleName
+ if (req.get) {
+ return req.get(context, deps, callback);
+ }
+
+ //Just return the module wanted. In this scenario, the
+ //second arg (if passed) is just the relModuleName.
+ moduleName = deps;
+ relModuleName = callback;
+ if (moduleName === "require" ||
+ moduleName === "exports" || moduleName === "module") {
+ return req.onError(new Error("Explicit require of " +
+ moduleName + " is not allowed."));
+ }
+
+ //Normalize module name, if it contains . or ..
+ nameProps = splitPrefix(moduleName, relModuleName);
+
+ ret = defined[nameProps.fullName];
+ if (ret === undefined) {
+ return req.onError(new Error("require: module name '" +
+ nameProps.fullName +
+ "' has not been loaded yet for context: " +
+ contextName));
+ }
+ return ret;
+ }
+
+ main(null, deps, callback, relModuleName);
+
+ //If the require call does not trigger anything new to load,
+ //then resume the dependency processing.
+ while (!context.scriptCount && context.paused.length) {
+ resume();
+ }
+ return undefined;
+ },
+
+ /**
+ * Internal method used by environment adapters to complete a load event.
+ * A load event could be a script load or just a load pass from a synchronous
+ * load call.
+ * @param {String} moduleName the name of the module to potentially complete.
+ */
+ completeLoad: function (moduleName) {
+ var args;
+
+ //Push all the globalDefQueue items into the context's defQueue
+ if (globalDefQueue.length) {
+ //Array splice in the values since the context code has a
+ //local var ref to defQueue, so cannot just reassign the one
+ //on context.
+ apsp.apply(context.defQueue,
+ [context.defQueue.length - 1, 0].concat(globalDefQueue));
+ globalDefQueue = [];
+ }
+
+ while (defQueue.length) {
+ args = defQueue.shift();
+
+ if (args[0] === null) {
+ args[0] = moduleName;
+ break;
+ } else if (args[0] === moduleName) {
+ //Found matching require.def call for this script!
+ break;
+ } else {
+ //Some other named require.def call, most likely the result
+ //of a build layer that included many require.def calls.
+ callDefMain(args);
+ args = null;
+ }
+ }
+ if (args) {
+ callDefMain(args);
+ } else {
+ //A script that does not call define(), so just simulate
+ //the call for it. Special exception for jQuery dynamic load.
+ callDefMain([moduleName, [],
+ moduleName === "jquery" && typeof jQuery !== "undefined" ?
+ function () {
+ return jQuery;
+ } : null]);
+ }
+
+ //Mark the script as loaded. Note that this can be different from a
+ //moduleName that maps to a require.def call. This line is important
+ //for traditional browser scripts.
+ loaded[moduleName] = true;
+
+ //If a global jQuery is defined, check for it. Need to do it here
+ //instead of main() since stock jQuery does not register as
+ //a module via define.
+ jQueryCheck();
+
+ //Doing this scriptCount decrement branching because sync envs
+ //need to decrement after resume, otherwise it looks like
+ //loading is complete after the first dependency is fetched.
+ //For browsers, it works fine to decrement after, but it means
+ //the checkLoaded setTimeout 50 ms cost is taken. To avoid
+ //that cost, decrement beforehand.
+ if (req.isAsync) {
+ context.scriptCount -= 1;
+ }
+ resume();
+ if (!req.isAsync) {
+ context.scriptCount -= 1;
+ }
+ },
+
+ /**
+ * Converts a module name + .extension into an URL path.
+ * *Requires* the use of a module name. It does not support using
+ * plain URLs like nameToUrl.
+ */
+ toUrl: function (moduleNamePlusExt, relModuleName) {
+ var index = moduleNamePlusExt.lastIndexOf('.'),
+ ext = null;
+
+ if (index !== -1) {
+ ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
+ moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
+ }
+
+ return context.nameToUrl(moduleNamePlusExt, ext, relModuleName);
+ },
+
+ /**
+ * Converts a module name to a file path. Supports cases where
+ * moduleName may actually be just an URL.
+ */
+ nameToUrl: function (moduleName, ext, relModuleName) {
+
+ var paths, packages, pkg, pkgPath, syms, i, parentModule, url,
+ config = context.config;
+
+ //Normalize module name if have a base relative module name to work from.
+ moduleName = normalizeName(moduleName, relModuleName);
+
+ //If a colon is in the URL, it indicates a protocol is used and it is just
+ //an URL to a file, or if it starts with a slash or ends with .js, it is just a plain file.
+ //The slash is important for protocol-less URLs as well as full paths.
+ if (req.jsExtRegExp.test(moduleName)) {
+ //Just a plain path, not module name lookup, so just return it.
+ //Add extension if it is included. This is a bit wonky, only non-.js things pass
+ //an extension, this method probably needs to be reworked.
+ url = moduleName + (ext ? ext : "");
+ } else {
+ //A module that needs to be converted to a path.
+ paths = config.paths;
+ packages = config.packages;
+
+ syms = moduleName.split("/");
+ //For each module name segment, see if there is a path
+ //registered for it. Start with most specific name
+ //and work up from it.
+ for (i = syms.length; i > 0; i--) {
+ parentModule = syms.slice(0, i).join("/");
+ if (paths[parentModule]) {
+ syms.splice(0, i, paths[parentModule]);
+ break;
+ } else if ((pkg = packages[parentModule])) {
+ //pkg can have just a string value to the path
+ //or can be an object with props:
+ //main, lib, name, location.
+ pkgPath = pkg.location + '/' + pkg.lib;
+ //If module name is just the package name, then looking
+ //for the main module.
+ if (moduleName === pkg.name) {
+ pkgPath += '/' + pkg.main;
+ }
+ syms.splice(0, i, pkgPath);
+ break;
+ }
+ }
+
+ //Join the path parts together, then figure out if baseUrl is needed.
+ url = syms.join("/") + (ext || ".js");
+ url = (url.charAt(0) === '/' || url.match(/^\w+:/) ? "" : config.baseUrl) + url;
+ }
+ return config.urlArgs ? url +
+ ((url.indexOf('?') === -1 ? '?' : '&') +
+ config.urlArgs) : url;
+ }
+ };
+
+ //Make these visible on the context so can be called at the very
+ //end of the file to bootstrap
+ context.jQueryCheck = jQueryCheck;
+ context.resume = resume;
+
+ return context;
+ }
+
+ /**
+ * Main entry point.
+ *
+ * If the only argument to require is a string, then the module that
+ * is represented by that string is fetched for the appropriate context.
+ *
+ * If the first argument is an array, then it will be treated as an array
+ * of dependency string names to fetch. An optional function callback can
+ * be specified to execute when all of those dependencies are available.
+ *
+ * Make a local req variable to help Caja compliance (it assumes things
+ * on a require that are not standardized), and to give a short
+ * name for minification/local scope use.
+ */
+ req = require = function (deps, callback) {
+
+ //Find the right context, use default
+ var contextName = defContextName,
+ context, config;
+
+ // Determine if have config object in the call.
+ if (!isArray(deps) && typeof deps !== "string") {
+ // deps is a config object
+ config = deps;
+ if (isArray(callback)) {
+ // Adjust args if there are dependencies
+ deps = callback;
+ callback = arguments[2];
+ } else {
+ deps = [];
+ }
+ }
+
+ if (config && config.context) {
+ contextName = config.context;
+ }
+
+ context = contexts[contextName] ||
+ (contexts[contextName] = newContext(contextName));
+
+ if (config) {
+ context.configure(config);
+ }
+
+ return context.require(deps, callback);
+ };
+
+ req.version = version;
+ req.isArray = isArray;
+ req.isFunction = isFunction;
+ req.mixin = mixin;
+ //Used to filter out dependencies that are already paths.
+ req.jsExtRegExp = /^\/|:|\?|\.js$/;
+ s = req.s = {
+ contexts: contexts,
+ //Stores a list of URLs that should not get async script tag treatment.
+ skipAsync: {},
+ isPageLoaded: !isBrowser,
+ readyCalls: []
+ };
+
+ req.isAsync = req.isBrowser = isBrowser;
+ if (isBrowser) {
+ head = s.head = document.getElementsByTagName("head")[0];
+ //If BASE tag is in play, using appendChild is a problem for IE6.
+ //When that browser dies, this can be removed. Details in this jQuery bug:
+ //http://dev.jquery.com/ticket/2709
+ baseElement = document.getElementsByTagName("base")[0];
+ if (baseElement) {
+ head = s.head = baseElement.parentNode;
+ }
+ }
+
+ /**
+ * Any errors that require explicitly generates will be passed to this
+ * function. Intercept/override it if you want custom error handling.
+ * @param {Error} err the error object.
+ */
+ req.onError = function (err) {
+ throw err;
+ };
+
+ /**
+ * Does the request to load a module for the browser case.
+ * Make this a separate function to allow other environments
+ * to override it.
+ *
+ * @param {Object} context the require context to find state.
+ * @param {String} moduleName the name of the module.
+ */
+ req.load = function (context, moduleName) {
+ var contextName = context.contextName,
+ urlFetched = context.urlFetched,
+ loaded = context.loaded, url;
+ isDone = false;
+
+ //Only set loaded to false for tracking if it has not already been set.
+ if (!loaded[moduleName]) {
+ loaded[moduleName] = false;
+ }
+
+ //First derive the path name for the module.
+ url = context.nameToUrl(moduleName);
+ if (!urlFetched[url]) {
+ context.scriptCount += 1;
+ req.attach(url, contextName, moduleName);
+ urlFetched[url] = true;
+
+ //If tracking a jQuery, then make sure its readyWait
+ //is incremented to prevent its ready callbacks from
+ //triggering too soon.
+ if (context.jQuery && !context.jQueryIncremented) {
+ context.jQuery.readyWait += 1;
+ context.jQueryIncremented = true;
+ }
+ }
+ };
+
+ function getInteractiveScript() {
+ var scripts, i, script;
+ if (interactiveScript && interactiveScript.readyState === 'interactive') {
+ return interactiveScript;
+ }
+
+ scripts = document.getElementsByTagName('script');
+ for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) {
+ if (script.readyState === 'interactive') {
+ return (interactiveScript = script);
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * The function that handles definitions of modules. Differs from
+ * require() in that a string for the module should be the first argument,
+ * and the function to execute after dependencies are loaded should
+ * return a value to define the module corresponding to the first argument's
+ * name.
+ */
+ define = req.def = function (name, deps, callback) {
+ var node, context;
+
+ //Allow for anonymous functions
+ if (typeof name !== 'string') {
+ //Adjust args appropriately
+ callback = deps;
+ deps = name;
+ name = null;
+ }
+
+ //This module may not have dependencies
+ if (!req.isArray(deps)) {
+ callback = deps;
+ deps = [];
+ }
+
+ //If no name, and callback is a function, then figure out if it a
+ //CommonJS thing with dependencies.
+ if (!name && !deps.length && req.isFunction(callback)) {
+ //Remove comments from the callback string,
+ //look for require calls, and pull them into the dependencies,
+ //but only if there are function args.
+ if (callback.length) {
+ callback
+ .toString()
+ .replace(commentRegExp, "")
+ .replace(cjsRequireRegExp, function (match, dep) {
+ deps.push(dep);
+ });
+
+ //May be a CommonJS thing even without require calls, but still
+ //could use exports, and such, so always add those as dependencies.
+ //This is a bit wasteful for RequireJS modules that do not need
+ //an exports or module object, but erring on side of safety.
+ //REQUIRES the function to expect the CommonJS variables in the
+ //order listed below.
+ deps = ["require", "exports", "module"].concat(deps);
+ }
+ }
+
+ //If in IE 6-8 and hit an anonymous define() call, do the interactive
+ //work.
+ if (useInteractive) {
+ node = currentlyAddingScript || getInteractiveScript();
+ if (!node) {
+ return req.onError(new Error("ERROR: No matching script interactive for " + callback));
+ }
+ if (!name) {
+ name = node.getAttribute("data-requiremodule");
+ }
+ context = contexts[node.getAttribute("data-requirecontext")];
+ }
+
+ //Always save off evaluating the def call until the script onload handler.
+ //This allows multiple modules to be in a file without prematurely
+ //tracing dependencies, and allows for anonymous module support,
+ //where the module name is not known until the script onload event
+ //occurs. If no context, use the global queue, and get it processed
+ //in the onscript load callback.
+ (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
+
+ return undefined;
+ };
+
+ /**
+ * Executes a module callack function. Broken out as a separate function
+ * solely to allow the build system to sequence the files in the built
+ * layer in the right sequence.
+ *
+ * @private
+ */
+ req.execCb = function (name, callback, args) {
+ return callback.apply(null, args);
+ };
+
+ /**
+ * callback for script loads, used to check status of loading.
+ *
+ * @param {Event} evt the event from the browser for the script
+ * that was loaded.
+ *
+ * @private
+ */
+ req.onScriptLoad = function (evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ var node = evt.currentTarget || evt.srcElement, contextName, moduleName,
+ context;
+
+ if (evt.type === "load" || readyRegExp.test(node.readyState)) {
+ //Reset interactive script so a script node is not held onto for
+ //to long.
+ interactiveScript = null;
+
+ //Pull out the name of the module and the context.
+ contextName = node.getAttribute("data-requirecontext");
+ moduleName = node.getAttribute("data-requiremodule");
+ context = contexts[contextName];
+
+ contexts[contextName].completeLoad(moduleName);
+
+ //Clean up script binding.
+ if (node.removeEventListener) {
+ node.removeEventListener("load", req.onScriptLoad, false);
+ } else {
+ //Probably IE. If not it will throw an error, which will be
+ //useful to know.
+ node.detachEvent("onreadystatechange", req.onScriptLoad);
+ }
+ }
+ };
+
+ /**
+ * Attaches the script represented by the URL to the current
+ * environment. Right now only supports browser loading,
+ * but can be redefined in other environments to do the right thing.
+ * @param {String} url the url of the script to attach.
+ * @param {String} contextName the name of the context that wants the script.
+ * @param {moduleName} the name of the module that is associated with the script.
+ * @param {Function} [callback] optional callback, defaults to require.onScriptLoad
+ * @param {String} [type] optional type, defaults to text/javascript
+ */
+ req.attach = function (url, contextName, moduleName, callback, type) {
+ var node, loaded, context;
+ if (isBrowser) {
+ //In the browser so use a script tag
+ callback = callback || req.onScriptLoad;
+ node = document.createElement("script");
+ node.type = type || "text/javascript";
+ node.charset = "utf-8";
+ //Use async so Gecko does not block on executing the script if something
+ //like a long-polling comet tag is being run first. Gecko likes
+ //to evaluate scripts in DOM order, even for dynamic scripts.
+ //It will fetch them async, but only evaluate the contents in DOM
+ //order, so a long-polling script tag can delay execution of scripts
+ //after it. But telling Gecko we expect async gets us the behavior
+ //we want -- execute it whenever it is finished downloading. Only
+ //Helps Firefox 3.6+
+ //Allow some URLs to not be fetched async. Mostly helps the order!
+ //plugin
+ node.async = !s.skipAsync[url];
+
+ node.setAttribute("data-requirecontext", contextName);
+ node.setAttribute("data-requiremodule", moduleName);
+
+ //Set up load listener.
+ if (node.addEventListener) {
+ node.addEventListener("load", callback, false);
+ } else {
+ //Probably IE. If not it will throw an error, which will be
+ //useful to know. IE (at least 6-8) do not fire
+ //script onload right after executing the script, so
+ //we cannot tie the anonymous require.def call to a name.
+ //However, IE reports the script as being in "interactive"
+ //readyState at the time of the require.def call.
+ useInteractive = true;
+ node.attachEvent("onreadystatechange", callback);
+ }
+ node.src = url;
+
+ //For some cache cases in IE 6-8, the script executes before the end
+ //of the appendChild execution, so to tie an anonymous require.def
+ //call to the module name (which is stored on the node), hold on
+ //to a reference to this node, but clear after the DOM insertion.
+ currentlyAddingScript = node;
+ if (baseElement) {
+ head.insertBefore(node, baseElement);
+ } else {
+ head.appendChild(node);
+ }
+ currentlyAddingScript = null;
+ return node;
+ } else if (isWebWorker) {
+ //In a web worker, use importScripts. This is not a very
+ //efficient use of importScripts, importScripts will block until
+ //its script is downloaded and evaluated. However, if web workers
+ //are in play, the expectation that a build has been done so that
+ //only one script needs to be loaded anyway. This may need to be
+ //reevaluated if other use cases become common.
+ context = contexts[contextName];
+ loaded = context.loaded;
+ loaded[moduleName] = false;
+
+ importScripts(url);
+
+ //Account for anonymous modules
+ context.completeLoad(moduleName);
+ }
+ return null;
+ };
+
+
+ //Determine what baseUrl should be if not already defined via a require config object
+ s.baseUrl = cfg.baseUrl;
+ if (isBrowser && (!s.baseUrl || !head)) {
+ //Figure out baseUrl. Get it from the script tag with require.js in it.
+ scripts = document.getElementsByTagName("script");
+ if (cfg.baseUrlMatch) {
+ rePkg = cfg.baseUrlMatch;
+ } else {
+
+
+
+ rePkg = /(allplugins-)?require\.js(\W|$)/i;
+
+ }
+
+ for (i = scripts.length - 1; i > -1 && (script = scripts[i]); i--) {
+ //Set the "head" where we can append children by
+ //using the script's parent.
+ if (!head) {
+ head = script.parentNode;
+ }
+
+
+ //Look for a data-main attribute to set main script for the page
+ //to load.
+ if (!dataMain && (dataMain = script.getAttribute('data-main'))) {
+ cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
+
+ //Favor using data-main tag as the base URL instead of
+ //trying to pattern-match src values.
+ if (!cfg.baseUrl && (src = script.src)) {
+ src = src.split('/');
+ src.pop();
+ //Make sure current config gets the value.
+ s.baseUrl = cfg.baseUrl = src.length ? src.join('/') : './';
+ }
+ }
+
+ //Using .src instead of getAttribute to get an absolute URL.
+ //While using a relative URL will be fine for script tags, other
+ //URLs used for text! resources that use XHR calls might benefit
+ //from an absolute URL.
+ if (!s.baseUrl && (src = script.src)) {
+ m = src.match(rePkg);
+ if (m) {
+ s.baseUrl = src.substring(0, m.index);
+ break;
+ }
+ }
+ }
+ }
+
+ //****** START page load functionality ****************
+ /**
+ * Sets the page as loaded and triggers check for all modules loaded.
+ */
+ req.pageLoaded = function () {
+ if (!s.isPageLoaded) {
+ s.isPageLoaded = true;
+ if (scrollIntervalId) {
+ clearInterval(scrollIntervalId);
+ }
+
+ //Part of a fix for FF < 3.6 where readyState was not set to
+ //complete so libraries like jQuery that check for readyState
+ //after page load where not getting initialized correctly.
+ //Original approach suggested by Andrea Giammarchi:
+ //http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html
+ //see other setReadyState reference for the rest of the fix.
+ if (setReadyState) {
+ document.readyState = "complete";
+ }
+
+ req.callReady();
+ }
+ };
+
+ //See if there is nothing waiting across contexts, and if not, trigger
+ //callReady.
+ req.checkReadyState = function () {
+ var contexts = s.contexts, prop;
+ for (prop in contexts) {
+ if (!(prop in empty)) {
+ if (contexts[prop].waitCount) {
+ return;
+ }
+ }
+ }
+ s.isDone = true;
+ req.callReady();
+ };
+
+ /**
+ * Internal function that calls back any ready functions. If you are
+ * integrating RequireJS with another library without require.ready support,
+ * you can define this method to call your page ready code instead.
+ */
+ req.callReady = function () {
+ var callbacks = s.readyCalls, i, callback, contexts, context, prop;
+
+ if (s.isPageLoaded && s.isDone) {
+ if (callbacks.length) {
+ s.readyCalls = [];
+ for (i = 0; (callback = callbacks[i]); i++) {
+ callback();
+ }
+ }
+
+ //If jQuery with readyWait is being tracked, updated its
+ //readyWait count.
+ contexts = s.contexts;
+ for (prop in contexts) {
+ if (!(prop in empty)) {
+ context = contexts[prop];
+ if (context.jQueryIncremented) {
+ context.jQuery.readyWait -= 1;
+ context.jQueryIncremented = false;
+ }
+ }
+ }
+ }
+ };
+
+ /**
+ * Registers functions to call when the page is loaded
+ */
+ req.ready = function (callback) {
+ if (s.isPageLoaded && s.isDone) {
+ callback();
+ } else {
+ s.readyCalls.push(callback);
+ }
+ return req;
+ };
+
+ if (isBrowser) {
+ if (document.addEventListener) {
+ //Standards. Hooray! Assumption here that if standards based,
+ //it knows about DOMContentLoaded.
+ document.addEventListener("DOMContentLoaded", req.pageLoaded, false);
+ window.addEventListener("load", req.pageLoaded, false);
+ //Part of FF < 3.6 readystate fix (see setReadyState refs for more info)
+ if (!document.readyState) {
+ setReadyState = true;
+ document.readyState = "loading";
+ }
+ } else if (window.attachEvent) {
+ window.attachEvent("onload", req.pageLoaded);
+
+ //DOMContentLoaded approximation, as found by Diego Perini:
+ //http://javascript.nwbox.com/IEContentLoaded/
+ if (self === self.top) {
+ scrollIntervalId = setInterval(function () {
+ try {
+ //From this ticket:
+ //http://bugs.dojotoolkit.org/ticket/11106,
+ //In IE HTML Application (HTA), such as in a selenium test,
+ //javascript in the iframe can't see anything outside
+ //of it, so self===self.top is true, but the iframe is
+ //not the top window and doScroll will be available
+ //before document.body is set. Test document.body
+ //before trying the doScroll trick.
+ if (document.body) {
+ document.documentElement.doScroll("left");
+ req.pageLoaded();
+ }
+ } catch (e) {}
+ }, 30);
+ }
+ }
+
+ //Check if document already complete, and if so, just trigger page load
+ //listeners. NOTE: does not work with Firefox before 3.6. To support
+ //those browsers, manually call require.pageLoaded().
+ if (document.readyState === "complete") {
+ req.pageLoaded();
+ }
+ }
+ //****** END page load functionality ****************
+
+ //Set up default context. If require was a configuration object, use that as base config.
+ req(cfg);
+
+ //If modules are built into require.js, then need to make sure dependencies are
+ //traced. Use a setTimeout in the browser world, to allow all the modules to register
+ //themselves. In a non-browser env, assume that modules are not built into require.js,
+ //which seems odd to do on the server.
+ if (typeof setTimeout !== "undefined") {
+ setTimeout(function () {
+ var ctx = s.contexts[(cfg.context || defContextName)];
+ //Allow for jQuery to be loaded/already in the page, and if jQuery 1.4.3,
+ //make sure to hold onto it for readyWait triggering.
+ ctx.jQueryCheck();
+ if (!ctx.scriptCount) {
+ ctx.resume();
+ }
+ req.checkReadyState();
+ }, 0);
+ }
+}());
+
Please sign in to comment.
Something went wrong with that request. Please try again.