3 * Copyright(c) 2006-2010 Ext JS, Inc.
5 * http://www.extjs.com/license
10 * Simple class to help load JavaScript files on demand
12 Ext.Loader = Ext.apply({}, {
14 * Loads a given set of .js files. Calls the callback function when all files have been loaded
15 * Set preserveOrder to true to ensure non-parallel loading of files if load order is important
16 * @param {Array} fileList Array of all files to load
17 * @param {Function} callback Callback to call after all files have been loaded
18 * @param {Object} scope The scope to call the callback in
19 * @param {Boolean} preserveOrder True to make files load in serial, one after the other (defaults to false)
21 load: function(fileList, callback, scope, preserveOrder) {
22 var scope = scope || this,
23 head = document.getElementsByTagName("head")[0],
24 fragment = document.createDocumentFragment(),
25 numFiles = fileList.length,
30 * Loads a particular file from the fileList by index. This is used when preserving order
32 var loadFileIndex = function(index) {
34 me.buildScriptTag(fileList[index], onFileLoaded)
39 * Callback function which is called after each file has been loaded. This calls the callback
40 * passed to load once the final file in the fileList has been loaded
42 var onFileLoaded = function() {
45 //if this was the last file, call the callback, otherwise load the next file
46 if (numFiles == loadedFiles && typeof callback == 'function') {
49 if (preserveOrder === true) {
50 loadFileIndex(loadedFiles);
55 if (preserveOrder === true) {
56 loadFileIndex.call(this, 0);
58 //load each file (most browsers will do this in parallel)
59 Ext.each(fileList, function(file, index) {
61 this.buildScriptTag(file, onFileLoaded)
65 head.appendChild(fragment);
71 * Creates and returns a script tag, but does not place it into the document. If a callback function
72 * is passed, this is called when the script has been loaded
73 * @param {String} filename The name of the file to create a script tag for
74 * @param {Function} callback Optional callback, which is called when the script has been loaded
75 * @return {Element} The new script ta
77 buildScriptTag: function(filename, callback) {
78 var script = document.createElement('script');
79 script.type = "text/javascript";
80 script.src = filename;
82 //IE has a different way of handling <script> loads, so we need to check for it here
83 if (script.readyState) {
84 script.onreadystatechange = function() {
85 if (script.readyState == "loaded" || script.readyState == "complete") {
86 script.onreadystatechange = null;
91 script.onload = callback;