ocLazyLoad.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  1. /**
  2. * oclazyload - Load modules on demand (lazy load) with angularJS
  3. * @version v1.0.9
  4. * @link https://github.com/ocombe/ocLazyLoad
  5. * @license MIT
  6. * @author Olivier Combe <olivier.combe@gmail.com>
  7. */
  8. (function (angular, window) {
  9. 'use strict';
  10. var regModules = ['ng', 'oc.lazyLoad'],
  11. regInvokes = {},
  12. regConfigs = [],
  13. modulesToLoad = [],
  14. // modules to load from angular.module or other sources
  15. realModules = [],
  16. // real modules called from angular.module
  17. recordDeclarations = [],
  18. broadcast = angular.noop,
  19. runBlocks = {},
  20. justLoaded = [];
  21. var ocLazyLoad = angular.module('oc.lazyLoad', ['ng']);
  22. ocLazyLoad.provider('$ocLazyLoad', ["$controllerProvider", "$provide", "$compileProvider", "$filterProvider", "$injector", "$animateProvider", function ($controllerProvider, $provide, $compileProvider, $filterProvider, $injector, $animateProvider) {
  23. var modules = {},
  24. providers = {
  25. $controllerProvider: $controllerProvider,
  26. $compileProvider: $compileProvider,
  27. $filterProvider: $filterProvider,
  28. $provide: $provide, // other things (constant, decorator, provider, factory, service)
  29. $injector: $injector,
  30. $animateProvider: $animateProvider
  31. },
  32. debug = false,
  33. events = false,
  34. moduleCache = [],
  35. modulePromises = {};
  36. moduleCache.push = function (value) {
  37. if (this.indexOf(value) === -1) {
  38. Array.prototype.push.apply(this, arguments);
  39. }
  40. };
  41. this.config = function (config) {
  42. // If we want to define modules configs
  43. if (angular.isDefined(config.modules)) {
  44. if (angular.isArray(config.modules)) {
  45. angular.forEach(config.modules, function (moduleConfig) {
  46. modules[moduleConfig.name] = moduleConfig;
  47. });
  48. } else {
  49. modules[config.modules.name] = config.modules;
  50. }
  51. }
  52. if (angular.isDefined(config.debug)) {
  53. debug = config.debug;
  54. }
  55. if (angular.isDefined(config.events)) {
  56. events = config.events;
  57. }
  58. };
  59. /**
  60. * Get the list of existing registered modules
  61. * @param element
  62. */
  63. this._init = function _init(element) {
  64. // this is probably useless now because we override angular.bootstrap
  65. if (modulesToLoad.length === 0) {
  66. var elements = [element],
  67. names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
  68. NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/,
  69. append = function append(elm) {
  70. return elm && elements.push(elm);
  71. };
  72. angular.forEach(names, function (name) {
  73. names[name] = true;
  74. append(document.getElementById(name));
  75. name = name.replace(':', '\\:');
  76. if (typeof element[0] !== 'undefined' && element[0].querySelectorAll) {
  77. angular.forEach(element[0].querySelectorAll('.' + name), append);
  78. angular.forEach(element[0].querySelectorAll('.' + name + '\\:'), append);
  79. angular.forEach(element[0].querySelectorAll('[' + name + ']'), append);
  80. }
  81. });
  82. angular.forEach(elements, function (elm) {
  83. if (modulesToLoad.length === 0) {
  84. var className = ' ' + element.className + ' ';
  85. var match = NG_APP_CLASS_REGEXP.exec(className);
  86. if (match) {
  87. modulesToLoad.push((match[2] || '').replace(/\s+/g, ','));
  88. } else {
  89. angular.forEach(elm.attributes, function (attr) {
  90. if (modulesToLoad.length === 0 && names[attr.name]) {
  91. modulesToLoad.push(attr.value);
  92. }
  93. });
  94. }
  95. }
  96. });
  97. }
  98. if (modulesToLoad.length === 0 && !((window.jasmine || window.mocha) && angular.isDefined(angular.mock))) {
  99. console.error('No module found during bootstrap, unable to init ocLazyLoad. You should always use the ng-app directive or angular.boostrap when you use ocLazyLoad.');
  100. }
  101. var addReg = function addReg(moduleName) {
  102. if (regModules.indexOf(moduleName) === -1) {
  103. // register existing modules
  104. regModules.push(moduleName);
  105. var mainModule = angular.module(moduleName);
  106. // register existing components (directives, services, ...)
  107. _invokeQueue(null, mainModule._invokeQueue, moduleName);
  108. _invokeQueue(null, mainModule._configBlocks, moduleName); // angular 1.3+
  109. angular.forEach(mainModule.requires, addReg);
  110. }
  111. };
  112. angular.forEach(modulesToLoad, function (moduleName) {
  113. addReg(moduleName);
  114. });
  115. modulesToLoad = []; // reset for next bootstrap
  116. recordDeclarations.pop(); // wait for the next lazy load
  117. };
  118. /**
  119. * Like JSON.stringify but that doesn't throw on circular references
  120. * @param obj
  121. */
  122. var stringify = function stringify(obj) {
  123. try {
  124. return JSON.stringify(obj);
  125. } catch (e) {
  126. var cache = [];
  127. return JSON.stringify(obj, function (key, value) {
  128. if (angular.isObject(value) && value !== null) {
  129. if (cache.indexOf(value) !== -1) {
  130. // Circular reference found, discard key
  131. return;
  132. }
  133. // Store value in our collection
  134. cache.push(value);
  135. }
  136. return value;
  137. });
  138. }
  139. };
  140. var hashCode = function hashCode(str) {
  141. var hash = 0,
  142. i,
  143. chr,
  144. len;
  145. if (str.length == 0) {
  146. return hash;
  147. }
  148. for (i = 0, len = str.length; i < len; i++) {
  149. chr = str.charCodeAt(i);
  150. hash = (hash << 5) - hash + chr;
  151. hash |= 0; // Convert to 32bit integer
  152. }
  153. return hash;
  154. };
  155. function _register(providers, registerModules, params) {
  156. if (registerModules) {
  157. var k,
  158. moduleName,
  159. moduleFn,
  160. tempRunBlocks = [];
  161. for (k = registerModules.length - 1; k >= 0; k--) {
  162. moduleName = registerModules[k];
  163. if (!angular.isString(moduleName)) {
  164. moduleName = getModuleName(moduleName);
  165. }
  166. if (!moduleName || justLoaded.indexOf(moduleName) !== -1 || modules[moduleName] && realModules.indexOf(moduleName) === -1) {
  167. continue;
  168. }
  169. // new if not registered
  170. var newModule = regModules.indexOf(moduleName) === -1;
  171. moduleFn = ngModuleFct(moduleName);
  172. if (newModule) {
  173. regModules.push(moduleName);
  174. _register(providers, moduleFn.requires, params);
  175. }
  176. if (moduleFn._runBlocks.length > 0) {
  177. // new run blocks detected! Replace the old ones (if existing)
  178. runBlocks[moduleName] = [];
  179. while (moduleFn._runBlocks.length > 0) {
  180. runBlocks[moduleName].push(moduleFn._runBlocks.shift());
  181. }
  182. }
  183. if (angular.isDefined(runBlocks[moduleName]) && (newModule || params.rerun)) {
  184. tempRunBlocks = tempRunBlocks.concat(runBlocks[moduleName]);
  185. }
  186. _invokeQueue(providers, moduleFn._invokeQueue, moduleName, params.reconfig);
  187. _invokeQueue(providers, moduleFn._configBlocks, moduleName, params.reconfig); // angular 1.3+
  188. broadcast(newModule ? 'ocLazyLoad.moduleLoaded' : 'ocLazyLoad.moduleReloaded', moduleName);
  189. registerModules.pop();
  190. justLoaded.push(moduleName);
  191. }
  192. // execute the run blocks at the end
  193. var instanceInjector = providers.getInstanceInjector();
  194. angular.forEach(tempRunBlocks, function (fn) {
  195. instanceInjector.invoke(fn);
  196. });
  197. }
  198. }
  199. function _registerInvokeList(args, moduleName) {
  200. var invokeList = args[2][0],
  201. type = args[1],
  202. newInvoke = false;
  203. if (angular.isUndefined(regInvokes[moduleName])) {
  204. regInvokes[moduleName] = {};
  205. }
  206. if (angular.isUndefined(regInvokes[moduleName][type])) {
  207. regInvokes[moduleName][type] = {};
  208. }
  209. var onInvoke = function onInvoke(invokeName, invoke) {
  210. if (!regInvokes[moduleName][type].hasOwnProperty(invokeName)) {
  211. regInvokes[moduleName][type][invokeName] = [];
  212. }
  213. if (checkHashes(invoke, regInvokes[moduleName][type][invokeName])) {
  214. newInvoke = true;
  215. regInvokes[moduleName][type][invokeName].push(invoke);
  216. broadcast('ocLazyLoad.componentLoaded', [moduleName, type, invokeName]);
  217. }
  218. };
  219. function checkHashes(potentialNew, invokes) {
  220. var isNew = true,
  221. newHash;
  222. if (invokes.length) {
  223. newHash = signature(potentialNew);
  224. angular.forEach(invokes, function (invoke) {
  225. isNew = isNew && signature(invoke) !== newHash;
  226. });
  227. }
  228. return isNew;
  229. }
  230. function signature(data) {
  231. if (angular.isArray(data)) {
  232. // arrays are objects, we need to test for it first
  233. return hashCode(data.toString());
  234. } else if (angular.isObject(data)) {
  235. // constants & values for example
  236. return hashCode(stringify(data));
  237. } else {
  238. if (angular.isDefined(data) && data !== null) {
  239. return hashCode(data.toString());
  240. } else {
  241. // null & undefined constants
  242. return data;
  243. }
  244. }
  245. }
  246. if (angular.isString(invokeList)) {
  247. onInvoke(invokeList, args[2][1]);
  248. } else if (angular.isObject(invokeList)) {
  249. angular.forEach(invokeList, function (invoke, key) {
  250. if (angular.isString(invoke)) {
  251. // decorators for example
  252. onInvoke(invoke, invokeList[1]);
  253. } else {
  254. // components registered as object lists {"componentName": function() {}}
  255. onInvoke(key, invoke);
  256. }
  257. });
  258. } else {
  259. return false;
  260. }
  261. return newInvoke;
  262. }
  263. function _invokeQueue(providers, queue, moduleName, reconfig) {
  264. if (!queue) {
  265. return;
  266. }
  267. var i, len, args, provider;
  268. for (i = 0, len = queue.length; i < len; i++) {
  269. args = queue[i];
  270. if (angular.isArray(args)) {
  271. if (providers !== null) {
  272. if (providers.hasOwnProperty(args[0])) {
  273. provider = providers[args[0]];
  274. } else {
  275. throw new Error('unsupported provider ' + args[0]);
  276. }
  277. }
  278. var isNew = _registerInvokeList(args, moduleName);
  279. if (args[1] !== 'invoke') {
  280. if (isNew && angular.isDefined(provider)) {
  281. provider[args[1]].apply(provider, args[2]);
  282. }
  283. } else {
  284. // config block
  285. var callInvoke = function callInvoke(fct) {
  286. var invoked = regConfigs.indexOf(moduleName + '-' + fct);
  287. if (invoked === -1 || reconfig) {
  288. if (invoked === -1) {
  289. regConfigs.push(moduleName + '-' + fct);
  290. }
  291. if (angular.isDefined(provider)) {
  292. provider[args[1]].apply(provider, args[2]);
  293. }
  294. }
  295. };
  296. if (angular.isFunction(args[2][0])) {
  297. callInvoke(args[2][0]);
  298. } else if (angular.isArray(args[2][0])) {
  299. for (var j = 0, jlen = args[2][0].length; j < jlen; j++) {
  300. if (angular.isFunction(args[2][0][j])) {
  301. callInvoke(args[2][0][j]);
  302. }
  303. }
  304. }
  305. }
  306. }
  307. }
  308. }
  309. function getModuleName(module) {
  310. var moduleName = null;
  311. if (angular.isString(module)) {
  312. moduleName = module;
  313. } else if (angular.isObject(module) && module.hasOwnProperty('name') && angular.isString(module.name)) {
  314. moduleName = module.name;
  315. }
  316. return moduleName;
  317. }
  318. function moduleExists(moduleName) {
  319. if (!angular.isString(moduleName)) {
  320. return false;
  321. }
  322. try {
  323. return ngModuleFct(moduleName);
  324. } catch (e) {
  325. if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) {
  326. return false;
  327. }
  328. }
  329. }
  330. this.$get = ["$log", "$rootElement", "$rootScope", "$cacheFactory", "$q", function ($log, $rootElement, $rootScope, $cacheFactory, $q) {
  331. var instanceInjector,
  332. filesCache = $cacheFactory('ocLazyLoad');
  333. if (!debug) {
  334. $log = {};
  335. $log['error'] = angular.noop;
  336. $log['warn'] = angular.noop;
  337. $log['info'] = angular.noop;
  338. }
  339. // Make this lazy because when $get() is called the instance injector hasn't been assigned to the rootElement yet
  340. providers.getInstanceInjector = function () {
  341. return instanceInjector ? instanceInjector : instanceInjector = $rootElement.data('$injector') || angular.injector();
  342. };
  343. broadcast = function broadcast(eventName, params) {
  344. if (events) {
  345. $rootScope.$broadcast(eventName, params);
  346. }
  347. if (debug) {
  348. $log.info(eventName, params);
  349. }
  350. };
  351. function reject(e) {
  352. var deferred = $q.defer();
  353. $log.error(e.message);
  354. deferred.reject(e);
  355. return deferred.promise;
  356. }
  357. return {
  358. _broadcast: broadcast,
  359. _$log: $log,
  360. /**
  361. * Returns the files cache used by the loaders to store the files currently loading
  362. * @returns {*}
  363. */
  364. _getFilesCache: function getFilesCache() {
  365. return filesCache;
  366. },
  367. /**
  368. * Let the service know that it should monitor angular.module because files are loading
  369. * @param watch boolean
  370. */
  371. toggleWatch: function toggleWatch(watch) {
  372. if (watch) {
  373. recordDeclarations.push(true);
  374. } else {
  375. recordDeclarations.pop();
  376. }
  377. },
  378. /**
  379. * Let you get a module config object
  380. * @param moduleName String the name of the module
  381. * @returns {*}
  382. */
  383. getModuleConfig: function getModuleConfig(moduleName) {
  384. if (!angular.isString(moduleName)) {
  385. throw new Error('You need to give the name of the module to get');
  386. }
  387. if (!modules[moduleName]) {
  388. return null;
  389. }
  390. return angular.copy(modules[moduleName]);
  391. },
  392. /**
  393. * Let you define a module config object
  394. * @param moduleConfig Object the module config object
  395. * @returns {*}
  396. */
  397. setModuleConfig: function setModuleConfig(moduleConfig) {
  398. if (!angular.isObject(moduleConfig)) {
  399. throw new Error('You need to give the module config object to set');
  400. }
  401. modules[moduleConfig.name] = moduleConfig;
  402. return moduleConfig;
  403. },
  404. /**
  405. * Returns the list of loaded modules
  406. * @returns {string[]}
  407. */
  408. getModules: function getModules() {
  409. return regModules;
  410. },
  411. /**
  412. * Let you check if a module has been loaded into Angular or not
  413. * @param modulesNames String/Object a module name, or a list of module names
  414. * @returns {boolean}
  415. */
  416. isLoaded: function isLoaded(modulesNames) {
  417. var moduleLoaded = function moduleLoaded(module) {
  418. var isLoaded = regModules.indexOf(module) > -1;
  419. if (!isLoaded) {
  420. isLoaded = !!moduleExists(module);
  421. }
  422. return isLoaded;
  423. };
  424. if (angular.isString(modulesNames)) {
  425. modulesNames = [modulesNames];
  426. }
  427. if (angular.isArray(modulesNames)) {
  428. var i, len;
  429. for (i = 0, len = modulesNames.length; i < len; i++) {
  430. if (!moduleLoaded(modulesNames[i])) {
  431. return false;
  432. }
  433. }
  434. return true;
  435. } else {
  436. throw new Error('You need to define the module(s) name(s)');
  437. }
  438. },
  439. /**
  440. * Given a module, return its name
  441. * @param module
  442. * @returns {String}
  443. */
  444. _getModuleName: getModuleName,
  445. /**
  446. * Returns a module if it exists
  447. * @param moduleName
  448. * @returns {module}
  449. */
  450. _getModule: function getModule(moduleName) {
  451. try {
  452. return ngModuleFct(moduleName);
  453. } catch (e) {
  454. // this error message really suxx
  455. if (/No module/.test(e) || e.message.indexOf('$injector:nomod') > -1) {
  456. e.message = 'The module "' + stringify(moduleName) + '" that you are trying to load does not exist. ' + e.message;
  457. }
  458. throw e;
  459. }
  460. },
  461. /**
  462. * Check if a module exists and returns it if it does
  463. * @param moduleName
  464. * @returns {boolean}
  465. */
  466. moduleExists: moduleExists,
  467. /**
  468. * Load the dependencies, and might try to load new files depending on the config
  469. * @param moduleName (String or Array of Strings)
  470. * @param localParams
  471. * @returns {*}
  472. * @private
  473. */
  474. _loadDependencies: function _loadDependencies(moduleName, localParams) {
  475. var loadedModule,
  476. requires,
  477. diff,
  478. promisesList = [],
  479. self = this;
  480. moduleName = self._getModuleName(moduleName);
  481. if (moduleName === null) {
  482. return $q.when();
  483. } else {
  484. try {
  485. loadedModule = self._getModule(moduleName);
  486. } catch (e) {
  487. return reject(e);
  488. }
  489. // get unloaded requires
  490. requires = self.getRequires(loadedModule);
  491. }
  492. angular.forEach(requires, function (requireEntry) {
  493. // If no configuration is provided, try and find one from a previous load.
  494. // If there isn't one, bail and let the normal flow run
  495. if (angular.isString(requireEntry)) {
  496. var config = self.getModuleConfig(requireEntry);
  497. if (config === null) {
  498. moduleCache.push(requireEntry); // We don't know about this module, but something else might, so push it anyway.
  499. return;
  500. }
  501. requireEntry = config;
  502. // ignore the name because it's probably not a real module name
  503. config.name = undefined;
  504. }
  505. // Check if this dependency has been loaded previously
  506. if (self.moduleExists(requireEntry.name)) {
  507. // compare against the already loaded module to see if the new definition adds any new files
  508. diff = requireEntry.files.filter(function (n) {
  509. return self.getModuleConfig(requireEntry.name).files.indexOf(n) < 0;
  510. });
  511. // If the module was redefined, advise via the console
  512. if (diff.length !== 0) {
  513. self._$log.warn('Module "', moduleName, '" attempted to redefine configuration for dependency. "', requireEntry.name, '"\n Additional Files Loaded:', diff);
  514. }
  515. // Push everything to the file loader, it will weed out the duplicates.
  516. if (angular.isDefined(self.filesLoader)) {
  517. // if a files loader is defined
  518. promisesList.push(self.filesLoader(requireEntry, localParams).then(function () {
  519. return self._loadDependencies(requireEntry);
  520. }));
  521. } else {
  522. return reject(new Error('Error: New dependencies need to be loaded from external files (' + requireEntry.files + '), but no loader has been defined.'));
  523. }
  524. return;
  525. } else if (angular.isArray(requireEntry)) {
  526. var files = [];
  527. angular.forEach(requireEntry, function (entry) {
  528. // let's check if the entry is a file name or a config name
  529. var config = self.getModuleConfig(entry);
  530. if (config === null) {
  531. files.push(entry);
  532. } else if (config.files) {
  533. files = files.concat(config.files);
  534. }
  535. });
  536. if (files.length > 0) {
  537. requireEntry = {
  538. files: files
  539. };
  540. }
  541. } else if (angular.isObject(requireEntry)) {
  542. if (requireEntry.hasOwnProperty('name') && requireEntry['name']) {
  543. // The dependency doesn't exist in the module cache and is a new configuration, so store and push it.
  544. self.setModuleConfig(requireEntry);
  545. moduleCache.push(requireEntry['name']);
  546. }
  547. }
  548. // Check if the dependency has any files that need to be loaded. If there are, push a new promise to the promise list.
  549. if (angular.isDefined(requireEntry.files) && requireEntry.files.length !== 0) {
  550. if (angular.isDefined(self.filesLoader)) {
  551. // if a files loader is defined
  552. promisesList.push(self.filesLoader(requireEntry, localParams).then(function () {
  553. return self._loadDependencies(requireEntry);
  554. }));
  555. } else {
  556. return reject(new Error('Error: the module "' + requireEntry.name + '" is defined in external files (' + requireEntry.files + '), but no loader has been defined.'));
  557. }
  558. }
  559. });
  560. // Create a wrapper promise to watch the promise list and resolve it once everything is done.
  561. return $q.all(promisesList);
  562. },
  563. /**
  564. * Inject new modules into Angular
  565. * @param moduleName
  566. * @param localParams
  567. * @param real
  568. */
  569. inject: function inject(moduleName) {
  570. var localParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  571. var real = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
  572. var self = this,
  573. deferred = $q.defer();
  574. if (angular.isDefined(moduleName) && moduleName !== null) {
  575. if (angular.isArray(moduleName)) {
  576. var promisesList = [];
  577. angular.forEach(moduleName, function (module) {
  578. promisesList.push(self.inject(module, localParams, real));
  579. });
  580. return $q.all(promisesList);
  581. } else {
  582. self._addToLoadList(self._getModuleName(moduleName), true, real);
  583. }
  584. }
  585. if (modulesToLoad.length > 0) {
  586. var res = modulesToLoad.slice(); // clean copy
  587. var loadNext = function loadNext(moduleName) {
  588. moduleCache.push(moduleName);
  589. modulePromises[moduleName] = deferred.promise;
  590. self._loadDependencies(moduleName, localParams).then(function success() {
  591. try {
  592. justLoaded = [];
  593. _register(providers, moduleCache, localParams);
  594. } catch (e) {
  595. self._$log.error(e.message);
  596. deferred.reject(e);
  597. return;
  598. }
  599. if (modulesToLoad.length > 0) {
  600. loadNext(modulesToLoad.shift()); // load the next in list
  601. } else {
  602. deferred.resolve(res); // everything has been loaded, resolve
  603. }
  604. }, function error(err) {
  605. deferred.reject(err);
  606. });
  607. };
  608. // load the first in list
  609. loadNext(modulesToLoad.shift());
  610. } else if (localParams && localParams.name && modulePromises[localParams.name]) {
  611. return modulePromises[localParams.name];
  612. } else {
  613. deferred.resolve();
  614. }
  615. return deferred.promise;
  616. },
  617. /**
  618. * Get the list of required modules/services/... for this module
  619. * @param module
  620. * @returns {Array}
  621. */
  622. getRequires: function getRequires(module) {
  623. var requires = [];
  624. angular.forEach(module.requires, function (requireModule) {
  625. if (regModules.indexOf(requireModule) === -1) {
  626. requires.push(requireModule);
  627. }
  628. });
  629. return requires;
  630. },
  631. /**
  632. * Invoke the new modules & component by their providers
  633. * @param providers
  634. * @param queue
  635. * @param moduleName
  636. * @param reconfig
  637. * @private
  638. */
  639. _invokeQueue: _invokeQueue,
  640. /**
  641. * Check if a module has been invoked and registers it if not
  642. * @param args
  643. * @param moduleName
  644. * @returns {boolean} is new
  645. */
  646. _registerInvokeList: _registerInvokeList,
  647. /**
  648. * Register a new module and loads it, executing the run/config blocks if needed
  649. * @param providers
  650. * @param registerModules
  651. * @param params
  652. * @private
  653. */
  654. _register: _register,
  655. /**
  656. * Add a module name to the list of modules that will be loaded in the next inject
  657. * @param name
  658. * @param force
  659. * @private
  660. */
  661. _addToLoadList: _addToLoadList,
  662. /**
  663. * Unregister modules (you shouldn't have to use this)
  664. * @param modules
  665. */
  666. _unregister: function _unregister(modules) {
  667. if (angular.isDefined(modules)) {
  668. if (angular.isArray(modules)) {
  669. angular.forEach(modules, function (module) {
  670. regInvokes[module] = undefined;
  671. });
  672. }
  673. }
  674. }
  675. };
  676. }];
  677. // Let's get the list of loaded modules & components
  678. this._init(angular.element(window.document));
  679. }]);
  680. var bootstrapFct = angular.bootstrap;
  681. angular.bootstrap = function (element, modules, config) {
  682. // we use slice to make a clean copy
  683. angular.forEach(modules.slice(), function (module) {
  684. _addToLoadList(module, true, true);
  685. });
  686. return bootstrapFct(element, modules, config);
  687. };
  688. var _addToLoadList = function _addToLoadList(name, force, real) {
  689. if ((recordDeclarations.length > 0 || force) && angular.isString(name) && modulesToLoad.indexOf(name) === -1) {
  690. modulesToLoad.push(name);
  691. if (real) {
  692. realModules.push(name);
  693. }
  694. }
  695. };
  696. var ngModuleFct = angular.module;
  697. angular.module = function (name, requires, configFn) {
  698. _addToLoadList(name, false, true);
  699. return ngModuleFct(name, requires, configFn);
  700. };
  701. // CommonJS package manager support:
  702. if (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) {
  703. module.exports = 'oc.lazyLoad';
  704. }
  705. })(angular, window);
  706. (function (angular) {
  707. 'use strict';
  708. angular.module('oc.lazyLoad').directive('ocLazyLoad', ["$ocLazyLoad", "$compile", "$animate", "$parse", "$timeout", function ($ocLazyLoad, $compile, $animate, $parse, $timeout) {
  709. return {
  710. restrict: 'A',
  711. terminal: true,
  712. priority: 1000,
  713. compile: function compile(element, attrs) {
  714. // we store the content and remove it before compilation
  715. var content = element[0].innerHTML;
  716. element.html('');
  717. return function ($scope, $element, $attr) {
  718. var model = $parse($attr.ocLazyLoad);
  719. $scope.$watch(function () {
  720. return model($scope) || $attr.ocLazyLoad; // it can be a module name (string), an object, an array, or a scope reference to any of this
  721. }, function (moduleName) {
  722. if (angular.isDefined(moduleName)) {
  723. $ocLazyLoad.load(moduleName).then(function () {
  724. // Attach element contents to DOM and then compile them.
  725. // This prevents an issue where IE invalidates saved element objects (HTMLCollections)
  726. // of the compiled contents when attaching to the parent DOM.
  727. $animate.enter(content, $element);
  728. // get the new content & compile it
  729. $compile($element.contents())($scope);
  730. });
  731. }
  732. }, true);
  733. };
  734. }
  735. };
  736. }]);
  737. })(angular);
  738. (function (angular) {
  739. 'use strict';
  740. angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
  741. $provide.decorator('$ocLazyLoad', ["$delegate", "$q", "$window", "$interval", function ($delegate, $q, $window, $interval) {
  742. var uaCssChecked = false,
  743. useCssLoadPatch = false,
  744. anchor = $window.document.getElementsByTagName('head')[0] || $window.document.getElementsByTagName('body')[0];
  745. /**
  746. * Load a js/css file
  747. * @param type
  748. * @param path
  749. * @param params
  750. * @returns promise
  751. */
  752. $delegate.buildElement = function buildElement(type, path, params) {
  753. var deferred = $q.defer(),
  754. el,
  755. loaded,
  756. filesCache = $delegate._getFilesCache(),
  757. cacheBuster = function cacheBuster(url) {
  758. var dc = new Date().getTime();
  759. if (url.indexOf('?') >= 0) {
  760. if (url.substring(0, url.length - 1) === '&') {
  761. return url + '_dc=' + dc;
  762. }
  763. return url + '&_dc=' + dc;
  764. } else {
  765. return url + '?_dc=' + dc;
  766. }
  767. };
  768. // Store the promise early so the file load can be detected by other parallel lazy loads
  769. // (ie: multiple routes on one page) a 'true' value isn't sufficient
  770. // as it causes false positive load results.
  771. if (angular.isUndefined(filesCache.get(path))) {
  772. filesCache.put(path, deferred.promise);
  773. }
  774. // Switch in case more content types are added later
  775. switch (type) {
  776. case 'css':
  777. el = $window.document.createElement('link');
  778. el.type = 'text/css';
  779. el.rel = 'stylesheet';
  780. el.href = params.cache === false ? cacheBuster(path) : path;
  781. break;
  782. case 'js':
  783. el = $window.document.createElement('script');
  784. el.src = params.cache === false ? cacheBuster(path) : path;
  785. break;
  786. default:
  787. filesCache.remove(path);
  788. deferred.reject(new Error('Requested type "' + type + '" is not known. Could not inject "' + path + '"'));
  789. break;
  790. }
  791. el.onload = el['onreadystatechange'] = function (e) {
  792. if (el['readyState'] && !/^c|loade/.test(el['readyState']) || loaded) return;
  793. el.onload = el['onreadystatechange'] = null;
  794. loaded = 1;
  795. $delegate._broadcast('ocLazyLoad.fileLoaded', path);
  796. deferred.resolve();
  797. };
  798. el.onerror = function () {
  799. filesCache.remove(path);
  800. deferred.reject(new Error('Unable to load ' + path));
  801. };
  802. el.async = params.serie ? 0 : 1;
  803. var insertBeforeElem = anchor.lastChild;
  804. if (params.insertBefore) {
  805. var element = angular.element(angular.isDefined(window.jQuery) ? params.insertBefore : document.querySelector(params.insertBefore));
  806. if (element && element.length > 0) {
  807. insertBeforeElem = element[0];
  808. }
  809. }
  810. insertBeforeElem.parentNode.insertBefore(el, insertBeforeElem);
  811. /*
  812. The event load or readystatechange doesn't fire in:
  813. - iOS < 6 (default mobile browser)
  814. - Android < 4.4 (default mobile browser)
  815. - Safari < 6 (desktop browser)
  816. */
  817. if (type == 'css') {
  818. if (!uaCssChecked) {
  819. var ua = $window.navigator.userAgent.toLowerCase();
  820. // iOS < 6
  821. if (/iP(hone|od|ad)/.test($window.navigator.platform)) {
  822. var v = $window.navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);
  823. var iOSVersion = parseFloat([parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)].join('.'));
  824. useCssLoadPatch = iOSVersion < 6;
  825. } else if (ua.indexOf("android") > -1) {
  826. // Android < 4.4
  827. var androidVersion = parseFloat(ua.slice(ua.indexOf("android") + 8));
  828. useCssLoadPatch = androidVersion < 4.4;
  829. } else if (ua.indexOf('safari') > -1) {
  830. var versionMatch = ua.match(/version\/([\.\d]+)/i);
  831. useCssLoadPatch = versionMatch && versionMatch[1] && parseFloat(versionMatch[1]) < 6;
  832. }
  833. }
  834. if (useCssLoadPatch) {
  835. var tries = 1000; // * 20 = 20000 miliseconds
  836. var interval = $interval(function () {
  837. try {
  838. el.sheet.cssRules;
  839. $interval.cancel(interval);
  840. el.onload();
  841. } catch (e) {
  842. if (--tries <= 0) {
  843. el.onerror();
  844. }
  845. }
  846. }, 20);
  847. }
  848. }
  849. return deferred.promise;
  850. };
  851. return $delegate;
  852. }]);
  853. }]);
  854. })(angular);
  855. (function (angular) {
  856. 'use strict';
  857. angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
  858. $provide.decorator('$ocLazyLoad', ["$delegate", "$q", function ($delegate, $q) {
  859. /**
  860. * The function that loads new files
  861. * @param config
  862. * @param params
  863. * @returns {*}
  864. */
  865. $delegate.filesLoader = function filesLoader(config) {
  866. var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  867. var cssFiles = [],
  868. templatesFiles = [],
  869. jsFiles = [],
  870. promises = [],
  871. cachePromise = null,
  872. filesCache = $delegate._getFilesCache();
  873. $delegate.toggleWatch(true); // start watching angular.module calls
  874. angular.extend(params, config);
  875. var pushFile = function pushFile(path) {
  876. var file_type = null,
  877. m;
  878. if (angular.isObject(path)) {
  879. file_type = path.type;
  880. path = path.path;
  881. }
  882. cachePromise = filesCache.get(path);
  883. if (angular.isUndefined(cachePromise) || params.cache === false) {
  884. // always check for requirejs syntax just in case
  885. if ((m = /^(css|less|html|htm|js)?(?=!)/.exec(path)) !== null) {
  886. // Detect file type using preceding type declaration (ala requireJS)
  887. file_type = m[1];
  888. path = path.substr(m[1].length + 1, path.length); // Strip the type from the path
  889. }
  890. if (!file_type) {
  891. if ((m = /[.](css|less|html|htm|js)?((\?|#).*)?$/.exec(path)) !== null) {
  892. // Detect file type via file extension
  893. file_type = m[1];
  894. } else if (!$delegate.jsLoader.hasOwnProperty('ocLazyLoadLoader') && $delegate.jsLoader.hasOwnProperty('requirejs')) {
  895. // requirejs
  896. file_type = 'js';
  897. } else {
  898. $delegate._$log.error('File type could not be determined. ' + path);
  899. return;
  900. }
  901. }
  902. if ((file_type === 'css' || file_type === 'less') && cssFiles.indexOf(path) === -1) {
  903. cssFiles.push(path);
  904. } else if ((file_type === 'html' || file_type === 'htm') && templatesFiles.indexOf(path) === -1) {
  905. templatesFiles.push(path);
  906. } else if (file_type === 'js' || jsFiles.indexOf(path) === -1) {
  907. jsFiles.push(path);
  908. } else {
  909. $delegate._$log.error('File type is not valid. ' + path);
  910. }
  911. } else if (cachePromise) {
  912. promises.push(cachePromise);
  913. }
  914. };
  915. if (params.serie) {
  916. pushFile(params.files.shift());
  917. } else {
  918. angular.forEach(params.files, function (path) {
  919. pushFile(path);
  920. });
  921. }
  922. if (cssFiles.length > 0) {
  923. var cssDeferred = $q.defer();
  924. $delegate.cssLoader(cssFiles, function (err) {
  925. if (angular.isDefined(err) && $delegate.cssLoader.hasOwnProperty('ocLazyLoadLoader')) {
  926. $delegate._$log.error(err);
  927. cssDeferred.reject(err);
  928. } else {
  929. cssDeferred.resolve();
  930. }
  931. }, params);
  932. promises.push(cssDeferred.promise);
  933. }
  934. if (templatesFiles.length > 0) {
  935. var templatesDeferred = $q.defer();
  936. $delegate.templatesLoader(templatesFiles, function (err) {
  937. if (angular.isDefined(err) && $delegate.templatesLoader.hasOwnProperty('ocLazyLoadLoader')) {
  938. $delegate._$log.error(err);
  939. templatesDeferred.reject(err);
  940. } else {
  941. templatesDeferred.resolve();
  942. }
  943. }, params);
  944. promises.push(templatesDeferred.promise);
  945. }
  946. if (jsFiles.length > 0) {
  947. var jsDeferred = $q.defer();
  948. $delegate.jsLoader(jsFiles, function (err) {
  949. if (angular.isDefined(err) && ($delegate.jsLoader.hasOwnProperty("ocLazyLoadLoader") || $delegate.jsLoader.hasOwnProperty("requirejs"))) {
  950. $delegate._$log.error(err);
  951. jsDeferred.reject(err);
  952. } else {
  953. jsDeferred.resolve();
  954. }
  955. }, params);
  956. promises.push(jsDeferred.promise);
  957. }
  958. if (promises.length === 0) {
  959. var deferred = $q.defer(),
  960. err = "Error: no file to load has been found, if you're trying to load an existing module you should use the 'inject' method instead of 'load'.";
  961. $delegate._$log.error(err);
  962. deferred.reject(err);
  963. return deferred.promise;
  964. } else if (params.serie && params.files.length > 0) {
  965. return $q.all(promises).then(function () {
  966. return $delegate.filesLoader(config, params);
  967. });
  968. } else {
  969. return $q.all(promises)['finally'](function (res) {
  970. $delegate.toggleWatch(false); // stop watching angular.module calls
  971. return res;
  972. });
  973. }
  974. };
  975. /**
  976. * Load a module or a list of modules into Angular
  977. * @param module Mixed the name of a predefined module config object, or a module config object, or an array of either
  978. * @param params Object optional parameters
  979. * @returns promise
  980. */
  981. $delegate.load = function (originalModule) {
  982. var originalParams = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  983. var self = this,
  984. config = null,
  985. deferredList = [],
  986. deferred = $q.defer(),
  987. errText;
  988. // clean copy
  989. var module = angular.copy(originalModule);
  990. var params = angular.copy(originalParams);
  991. // If module is an array, break it down
  992. if (angular.isArray(module)) {
  993. // Resubmit each entry as a single module
  994. angular.forEach(module, function (m) {
  995. deferredList.push(self.load(m, params));
  996. });
  997. // Resolve the promise once everything has loaded
  998. $q.all(deferredList).then(function (res) {
  999. deferred.resolve(res);
  1000. }, function (err) {
  1001. deferred.reject(err);
  1002. });
  1003. return deferred.promise;
  1004. }
  1005. // Get or Set a configuration depending on what was passed in
  1006. if (angular.isString(module)) {
  1007. config = self.getModuleConfig(module);
  1008. if (!config) {
  1009. config = {
  1010. files: [module]
  1011. };
  1012. }
  1013. } else if (angular.isObject(module)) {
  1014. // case {type: 'js', path: lazyLoadUrl + 'testModule.fakejs'}
  1015. if (angular.isDefined(module.path) && angular.isDefined(module.type)) {
  1016. config = {
  1017. files: [module]
  1018. };
  1019. } else {
  1020. config = self.setModuleConfig(module);
  1021. }
  1022. }
  1023. if (config === null) {
  1024. var moduleName = self._getModuleName(module);
  1025. errText = 'Module "' + (moduleName || 'unknown') + '" is not configured, cannot load.';
  1026. $delegate._$log.error(errText);
  1027. deferred.reject(new Error(errText));
  1028. return deferred.promise;
  1029. } else {
  1030. // deprecated
  1031. if (angular.isDefined(config.template)) {
  1032. if (angular.isUndefined(config.files)) {
  1033. config.files = [];
  1034. }
  1035. if (angular.isString(config.template)) {
  1036. config.files.push(config.template);
  1037. } else if (angular.isArray(config.template)) {
  1038. config.files.concat(config.template);
  1039. }
  1040. }
  1041. }
  1042. var localParams = angular.extend({}, params, config);
  1043. // if someone used an external loader and called the load function with just the module name
  1044. if (angular.isUndefined(config.files) && angular.isDefined(config.name) && $delegate.moduleExists(config.name)) {
  1045. return $delegate.inject(config.name, localParams, true);
  1046. }
  1047. $delegate.filesLoader(config, localParams).then(function () {
  1048. $delegate.inject(null, localParams).then(function (res) {
  1049. deferred.resolve(res);
  1050. }, function (err) {
  1051. deferred.reject(err);
  1052. });
  1053. }, function (err) {
  1054. deferred.reject(err);
  1055. });
  1056. return deferred.promise;
  1057. };
  1058. // return the patched service
  1059. return $delegate;
  1060. }]);
  1061. }]);
  1062. })(angular);
  1063. (function (angular) {
  1064. 'use strict';
  1065. angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
  1066. $provide.decorator('$ocLazyLoad', ["$delegate", "$q", function ($delegate, $q) {
  1067. /**
  1068. * cssLoader function
  1069. * @type Function
  1070. * @param paths array list of css files to load
  1071. * @param callback to call when everything is loaded. We use a callback and not a promise
  1072. * @param params object config parameters
  1073. * because the user can overwrite cssLoader and it will probably not use promises :(
  1074. */
  1075. $delegate.cssLoader = function (paths, callback, params) {
  1076. var promises = [];
  1077. angular.forEach(paths, function (path) {
  1078. promises.push($delegate.buildElement('css', path, params));
  1079. });
  1080. $q.all(promises).then(function () {
  1081. callback();
  1082. }, function (err) {
  1083. callback(err);
  1084. });
  1085. };
  1086. $delegate.cssLoader.ocLazyLoadLoader = true;
  1087. return $delegate;
  1088. }]);
  1089. }]);
  1090. })(angular);
  1091. (function (angular) {
  1092. 'use strict';
  1093. angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
  1094. $provide.decorator('$ocLazyLoad', ["$delegate", "$q", function ($delegate, $q) {
  1095. /**
  1096. * jsLoader function
  1097. * @type Function
  1098. * @param paths array list of js files to load
  1099. * @param callback to call when everything is loaded. We use a callback and not a promise
  1100. * @param params object config parameters
  1101. * because the user can overwrite jsLoader and it will probably not use promises :(
  1102. */
  1103. $delegate.jsLoader = function (paths, callback, params) {
  1104. var promises = [];
  1105. angular.forEach(paths, function (path) {
  1106. promises.push($delegate.buildElement('js', path, params));
  1107. });
  1108. $q.all(promises).then(function () {
  1109. callback();
  1110. }, function (err) {
  1111. callback(err);
  1112. });
  1113. };
  1114. $delegate.jsLoader.ocLazyLoadLoader = true;
  1115. return $delegate;
  1116. }]);
  1117. }]);
  1118. })(angular);
  1119. (function (angular) {
  1120. 'use strict';
  1121. angular.module('oc.lazyLoad').config(["$provide", function ($provide) {
  1122. $provide.decorator('$ocLazyLoad', ["$delegate", "$templateCache", "$q", "$http", function ($delegate, $templateCache, $q, $http) {
  1123. /**
  1124. * templatesLoader function
  1125. * @type Function
  1126. * @param paths array list of css files to load
  1127. * @param callback to call when everything is loaded. We use a callback and not a promise
  1128. * @param params object config parameters for $http
  1129. * because the user can overwrite templatesLoader and it will probably not use promises :(
  1130. */
  1131. $delegate.templatesLoader = function (paths, callback, params) {
  1132. var promises = [],
  1133. filesCache = $delegate._getFilesCache();
  1134. angular.forEach(paths, function (url) {
  1135. var deferred = $q.defer();
  1136. promises.push(deferred.promise);
  1137. $http.get(url, params).success(function (data) {
  1138. if (angular.isString(data) && data.length > 0) {
  1139. angular.forEach(angular.element(data), function (node) {
  1140. if (node.nodeName === 'SCRIPT' && node.type === 'text/ng-template') {
  1141. $templateCache.put(node.id, node.innerHTML);
  1142. }
  1143. });
  1144. }
  1145. if (angular.isUndefined(filesCache.get(url))) {
  1146. filesCache.put(url, true);
  1147. }
  1148. deferred.resolve();
  1149. }).error(function (err) {
  1150. deferred.reject(new Error('Unable to load template file "' + url + '": ' + err));
  1151. });
  1152. });
  1153. return $q.all(promises).then(function () {
  1154. callback();
  1155. }, function (err) {
  1156. callback(err);
  1157. });
  1158. };
  1159. $delegate.templatesLoader.ocLazyLoadLoader = true;
  1160. return $delegate;
  1161. }]);
  1162. }]);
  1163. })(angular);
  1164. // Array.indexOf polyfill for IE8
  1165. if (!Array.prototype.indexOf) {
  1166. Array.prototype.indexOf = function (searchElement, fromIndex) {
  1167. var k;
  1168. // 1. Let O be the result of calling ToObject passing
  1169. // the this value as the argument.
  1170. if (this == null) {
  1171. throw new TypeError('"this" is null or not defined');
  1172. }
  1173. var O = Object(this);
  1174. // 2. Let lenValue be the result of calling the Get
  1175. // internal method of O with the argument "length".
  1176. // 3. Let len be ToUint32(lenValue).
  1177. var len = O.length >>> 0;
  1178. // 4. If len is 0, return -1.
  1179. if (len === 0) {
  1180. return -1;
  1181. }
  1182. // 5. If argument fromIndex was passed let n be
  1183. // ToInteger(fromIndex); else let n be 0.
  1184. var n = +fromIndex || 0;
  1185. if (Math.abs(n) === Infinity) {
  1186. n = 0;
  1187. }
  1188. // 6. If n >= len, return -1.
  1189. if (n >= len) {
  1190. return -1;
  1191. }
  1192. // 7. If n >= 0, then Let k be n.
  1193. // 8. Else, n<0, Let k be len - abs(n).
  1194. // If k is less than 0, then let k be 0.
  1195. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
  1196. // 9. Repeat, while k < len
  1197. while (k < len) {
  1198. // a. Let Pk be ToString(k).
  1199. // This is implicit for LHS operands of the in operator
  1200. // b. Let kPresent be the result of calling the
  1201. // HasProperty internal method of O with argument Pk.
  1202. // This step can be combined with c
  1203. // c. If kPresent is true, then
  1204. // i. Let elementK be the result of calling the Get
  1205. // internal method of O with the argument ToString(k).
  1206. // ii. Let same be the result of applying the
  1207. // Strict Equality Comparison Algorithm to
  1208. // searchElement and elementK.
  1209. // iii. If same is true, return k.
  1210. if (k in O && O[k] === searchElement) {
  1211. return k;
  1212. }
  1213. k++;
  1214. }
  1215. return -1;
  1216. };
  1217. }