LoadQueue Class
The LoadQueue class is the main API for preloading content. LoadQueue is a load manager, which can preload either a single file, or queue of files.
Creating a Queue
To use LoadQueue, create a LoadQueue instance. If you want to force tag loading where possible, set the preferXHR
argument to false.
var queue = new createjs.LoadQueue(true);
Listening for Events
Add any listeners you want to the queue. Since PreloadJS 0.3.0, the EventDispatcher
lets you add as many listeners as you want for events. You can subscribe to the following events:
- complete: fired when a queue completes loading all files
- error: fired when the queue encounters an error with any file.
- progress: Progress for the entire queue has changed.
- fileload: A single file has completed loading.
- fileprogress: Progress for a single file has changes. Note that only files loaded with XHR (or possibly by plugins) will fire progress events other than 0 or 100%.
queue.on("fileload", handleFileLoad, this);
queue.on("complete", handleComplete, this);
Adding files and manifests
Add files you want to load using loadFile or add multiple files at a
time using a list or a manifest definition using loadManifest. Files are
appended to the end of the active queue, so you can use these methods as many times as you like, whenever you
like.
queue.loadFile("filePath/file.jpg");
queue.loadFile({id:"image", src:"filePath/file.jpg"});
queue.loadManifest(["filePath/file.jpg", {id:"image", src:"filePath/file.jpg"}]);
// Use an external manifest
queue.loadManifest("path/to/manifest.json");
queue.loadManifest({src:"manifest.json", type:"manifest"});
If you pass false
as the loadNow
parameter, the queue will not kick of the load of the files, but it will not
stop if it has already been started. Call the load method to begin
a paused queue. Note that a paused queue will automatically resume when new files are added to it with a
loadNow
argument of true
.
queue.load();
File Types
The file type of a manifest item is auto-determined by the file extension. The pattern matching in PreloadJS
should handle the majority of standard file and url formats, and works with common file extensions. If you have
either a non-standard file extension, or are serving the file using a proxy script, then you can pass in a
type
property with any manifest item.
queue.loadFile({src:"path/to/myFile.mp3x", type:createjs.Types.SOUND});
// Note that PreloadJS will not read a file extension from the query string
queue.loadFile({src:"http://server.com/proxy?file=image.jpg", type:createjs.Types.IMAGE});
Supported types are defined on the AbstractLoader class, and include:
- BINARY: Raw binary data via XHR
- CSS: CSS files
- IMAGE: Common image formats
- JAVASCRIPT: JavaScript files
- JSON: JSON data
- JSONP: JSON files cross-domain
- MANIFEST: A list of files to load in JSON format, see AbstractLoader/loadManifest
- SOUND: Audio file formats
- SPRITESHEET: JSON SpriteSheet definitions. This will also load sub-images, and provide a SpriteSheet instance.
- SVG: SVG files
- TEXT: Text files - XHR only
- VIDEO: Video objects
- XML: XML data
Note: Loader types used to be defined on LoadQueue, but have been moved to the Types class
Handling Results
When a file is finished downloading, a fileload event is
dispatched. In an example above, there is an event listener snippet for fileload. Loaded files are usually a
formatted object that can be used immediately, including:
- Binary: The binary loaded result
- CSS: A <link /> tag
- Image: An <img /> tag
- JavaScript: A <script /> tag
- JSON/JSONP: A formatted JavaScript Object
- Manifest: A JavaScript object.
- Sound: An <audio /> tag
- SpriteSheet: A SpriteSheet instance, containing loaded images.
- SVG: An <object /> tag
- Text: Raw text
- Video: A Video DOM node
- XML: An XML DOM node
function handleFileLoad(event) {
var item = event.item; // A reference to the item that was passed in to the LoadQueue
var type = item.type;
// Add any images to the page body.
if (type == createjs.Types.IMAGE) {
document.body.appendChild(event.result);
}
}
At any time after the file has been loaded (usually after the queue has completed), any result can be looked up
via its "id" using getResult. If no id was provided, then the
"src" or file path can be used instead, including the path
defined by a manifest, but not including
a base path defined on the LoadQueue. It is recommended to always pass an id if you want to look up content.
var image = queue.getResult("image");
document.body.appendChild(image);
Raw loaded content can be accessed using the rawResult
property of the fileload
event, or can be looked up using getResult, passing true
as the 2nd
argument. This is only applicable for content that has been parsed for the browser, specifically: JavaScript,
CSS, XML, SVG, and JSON objects, or anything loaded with XHR.
var image = queue.getResult("image", true); // load the binary image data loaded with XHR.
Plugins
LoadQueue has a simple plugin architecture to help process and preload content. For example, to preload audio,
make sure to install the SoundJS Sound class, which will help load HTML audio,
Flash audio, and WebAudio files. This should be installed before loading any audio files.
queue.installPlugin(createjs.Sound);
Known Browser Issues
- Browsers without audio support can not load audio files.
- Safari on Mac OS X can only play HTML audio if QuickTime is installed
- HTML Audio tags will only download until their
canPlayThrough
event is fired. Browsers other than Chrome will continue to download in the background. - When loading scripts using tags, they are automatically added to the document.
- Scripts loaded via XHR may not be properly inspectable with browser tools.
- IE6 and IE7 (and some other browsers) may not be able to load XML, Text, or JSON, since they require XHR to work.
- Content loaded via tags will not show progress, and will continue to download in the background when canceled, although no events will be dispatched.
Constructor
LoadQueue
-
[preferXHR=true]
-
[basePath=""]
-
[crossOrigin=""]
Parameters:
-
[preferXHR=true]
Boolean optionalDetermines whether the preload instance will favor loading with XHR (XML HTTP Requests), or HTML tags. When this is
false
, the queue will use tag loading when possible, and fall back on XHR when necessary. -
[basePath=""]
String optionalA path that will be prepended on to the source parameter of all items in the queue before they are loaded. Sources beginning with a protocol such as
http://
or a relative path such as../
will not receive a base path. -
[crossOrigin=""]
String | Boolean optionalAn optional flag to support images loaded from a CORS-enabled server. To use it, set this value to
true
, which will default the crossOrigin property on images to "Anonymous". Any string value will be passed through, but only "" and "Anonymous" are recommended. Note: The crossOrigin parameter is deprecated. Use LoadItem.crossOrigin instead
Item Index
Methods
- _addItem
- _canStartLoad
- _checkScriptLoadOrder
- _createLoader
- _createLoadItem
- _createRequest
- _createTag
- _dispatchEvent
- _disposeItem
- _finishOrderedItem
- _handleError
- _handleFileComplete
- _handleProgress
- _isCanceled
- _loadItem
- _loadNext
- _processFinishedLoad
- _removeLoadItem
- _resultFormatSuccess
- _saveLoadedItems
- _sendComplete
- _sendError
- _sendFileComplete
- _sendFileProgress
- _sendFileStart
- _sendLoadStart
- _sendProgress
- _updateProgress
- addEventListener
- cancel
- close
- destroy
- dispatchEvent
- getItem
- getItems
- getLoadedItems
- getResult
- getTag
- handleEvent
- hasEventListener
- init
- installPlugin
- load
- loadFile
- loadManifest
- off
- on
- registerLoader
- remove
- removeAll
- removeAllEventListeners
- removeEventListener
- reset
- setMaxConnections
- setPaused
- setPreferXHR
- setTag
- toString
- unregisterLoader
- willTrigger
Properties
- _availableLoaders
- _basePath
- _captureListeners
- _crossOrigin
- _currentLoads
- _currentlyLoadingScript
- _defaultLoaderLength
- _extensionCallbacks
- _item
- _lastProgress
- _listeners
- _loadedRawResults
- _loadedResults
- _loadedScripts
- _loadItems
- _loadItemsById
- _loadItemsBySrc
- _loadQueue
- _loadQueueBackup
- _loadStartWasDispatched
- _maxConnections
- _numItems
- _numItemsLoaded
- _paused
- _plugins
- _preferXHR
- _rawResult
- _result
- _scriptOrder
- _tag
- _typeCallbacks
- canceled
- loaded
- maintainScriptOrder
- next
- progress
- resultFormatter
- stopOnError
- type
Methods
_addItem
-
value
-
[path]
-
[basePath]
Add an item to the queue. Items are formatted into a usable object containing all the properties necessary to load the content. The load queue is populated with the loader instance that handles preloading, and not the load item that was passed in by the user. To look up the load item by id or src, use the LoadQueue.getItem method.
Parameters:
-
value
String | ObjectThe item to add to the queue.
-
[path]
String optionalAn optional path prepended to the
src
. The path will only be prepended if the src is relative, and does not start with a protocol such ashttp://
, or a path like../
. If the LoadQueue was provided a _basePath, then it will optionally be prepended after. -
[basePath]
String optionalDeprecatedAn optional basePath passed into a loadManifest or loadFile call. This parameter will be removed in a future tagged version.
_canStartLoad
-
loader
Ensure items with maintainOrder=true
that are before the specified item have loaded. This only applies to
JavaScript items that are being loaded with a TagLoader, since they have to be loaded and completed before
the script can even be started, since it exist in the DOM while loading.
Parameters:
-
loader
AbstractLoaderThe loader for the item
Returns:
Whether the item can start a load or not.
_checkScriptLoadOrder
()
private
Ensure the scripts load and dispatch in the correct order. When using XHR, scripts are stored in an array in the
order they were added, but with a "null" value. When they are completed, the value is set to the load item,
and then when they are processed and dispatched, the value is set to true
. This method simply
iterates the array, and ensures that any loaded items that are not preceded by a null
value are
dispatched.
_createLoader
-
item
Create a loader for a load item.
Parameters:
-
item
ObjectA formatted load item that can be used to generate a loader.
Returns:
A loader that can be used to load content.
_createLoadItem
-
value
-
[path]
-
[basePath]
Create a refined LoadItem, which contains all the required properties. The type of item is determined by browser support, requirements based on the file type, and developer settings. For example, XHR is only used for file types that support it in new browsers.
Before the item is returned, any plugins registered to handle the type or extension will be fired, which may alter the load item.
Parameters:
-
value
String | Object | HTMLAudioElement | HTMLImageElementThe item that needs to be preloaded.
-
[path]
String optionalA path to prepend to the item's source. Sources beginning with http:// or similar will not receive a path. Since PreloadJS 0.4.1, the src will be modified to include the
path
and _basePath when it is added. -
[basePath]
String optionalDeprectated A base path to prepend to the items source in addition to the path argument.
Returns:
The loader instance that will be used.
_createRequest
()
protected
Create an internal request used for loading. By default, an XHRRequest or TagRequest is created, depending on the value of PreferXHR:property. Other loaders may override this to use different request types, such as ManifestLoader, which uses JSONLoader or JSONPLoader under the hood.
_createTag
-
src
Create the HTML tag used for loading. This method does nothing by default, and needs to be implemented by loaders that require tag loading.
Parameters:
-
src
StringThe tag source
Returns:
The tag that was created
_dispatchEvent
-
eventObj
-
eventPhase
_disposeItem
-
item
Clean out item results, to free them from memory. Mainly, the loaded item and results are cleared from internal hashes.
_finishOrderedItem
-
loader
-
loadFailed
Flag an item as finished. If the item's order is being managed, then ensure that it is allowed to finish, and if so, trigger prior items to trigger as well.
Parameters:
-
loader
AbstractLoader -
loadFailed
Boolean
Returns:
If the item's order is being managed. This allows the caller to take an alternate behaviour if it is.
_handleError
-
event
The callback that is fired when a loader encounters an error. The queue will continue loading unless stopOnError
is set to true
.
Parameters:
-
event
ErrorEventThe error event, containing relevant error information.
_handleFileComplete
-
event
An item has finished loading. We can assume that it is totally loaded, has been parsed for immediate use, and is available as the "result" property on the load item. The raw text result for a parsed item (such as JSON, XML, CSS, JavaScript, etc) is available as the "rawResult" property, and can also be looked up using getResult.
Parameters:
-
event
EventThe event object from the loader.
_handleProgress
-
event
An item has dispatched progress. Propagate that progress, and update the LoadQueue's overall progress.
Parameters:
-
event
ProgressEventThe progress event from the item.
_isCanceled
()
Boolean
protected
Determine if the load has been canceled. This is important to ensure that method calls or asynchronous events do not cause issues after the queue has been cleaned up.
Returns:
If the loader has been canceled.
_loadItem
-
loader
Begin loading an item. Event listeners are not added to the loaders until the load starts.
Parameters:
-
loader
AbstractLoaderThe loader instance to start. Currently, this will be an XHRLoader or TagLoader.
_loadNext
()
private
Load the next item in the queue. If the queue is empty (all items have been loaded), then the complete event is processed. The queue will "fill up" any empty slots, up to the max connection specified using LoadQueue.setMaxConnections method. The only exception is scripts that are loaded using tags, which have to be loaded one at a time to maintain load order.
_processFinishedLoad
-
item
-
loader
A file has completed loading, and the LoadQueue can move on. This triggers the complete event, and kick-starts the next item.
Parameters:
-
item
LoadItem | Object -
loader
AbstractLoader
_removeLoadItem
-
loader
A load item is completed or was canceled, and needs to be removed from the LoadQueue.
Parameters:
-
loader
AbstractLoaderA loader instance to remove.
_resultFormatSuccess
-
result
The "success" callback passed to AbstractLoader/resultFormatter asynchronous functions.
Parameters:
-
result
ObjectThe formatted result
_saveLoadedItems
-
loader
Some loaders might load additional content, other than the item they were passed (such as ManifestLoader). Any items exposed by the loader using AbstractLoader/getLoadItems are added to the LoadQueue's look-ups, including GetItem and GetResult methods.
Parameters:
-
loader
AbstractLoader
_sendError
-
event
Parameters:
-
event
ErrorEventThe event object containing specific error properties.
_sendFileComplete
-
item
-
loader
Parameters:
-
item
LoadItemObjectThe item that is being loaded.
-
loader
AbstractLoader
_sendFileProgress
-
item
-
progress
Dispatch a "fileprogress" Event. Please see the LoadQueue fileprogress event for details on the event payload.
_sendFileStart
-
item
_sendLoadStart
()
protected
_updateProgress
()
private
Overall progress has changed, so determine the new progress amount and dispatch it. This changes any time an item dispatches progress or completes. Note that since we don't always know the actual filesize of items before they are loaded. In this case, we define a "slot" for each item (1 item in 10 would get 10%), and then append loaded progress on top of the already-loaded items.
For example, if 5/10 items have loaded, and item 6 is 20% loaded, the total progress would be:
- 5/10 of the items in the queue (50%)
- plus 20% of item 6's slot (2%)
- equals 52%
addEventListener
-
type
-
listener
-
[useCapture]
Adds the specified event listener. Note that adding multiple listeners to the same function will result in multiple callbacks getting fired.
Example
displayObject.addEventListener("click", handleClick);
function handleClick(event) {
// Click happened.
}
Parameters:
-
type
StringThe string type of the event.
-
listener
Function | ObjectAn object with a handleEvent method, or a function that will be called when the event is dispatched.
-
[useCapture]
Boolean optionalFor events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
cancel
()
Close the the item. This will stop any open requests (although downloads using HTML tags may still continue in the background), but events will not longer be dispatched.
close
()
Close the active queue. Closing a queue completely empties the queue, and prevents any remaining items from starting to download. Note that currently any active loads will remain open, and events may be processed.
To stop and restart a queue, use the setPaused method instead.
destroy
()
Clean up the loader.
dispatchEvent
-
eventObj
-
[bubbles]
-
[cancelable]
Dispatches the specified event to all listeners.
Example
// Use a string event
this.dispatchEvent("complete");
// Use an Event instance
var event = new createjs.Event("progress");
this.dispatchEvent(event);
Parameters:
-
eventObj
Object | String | EventAn object with a "type" property, or a string type. While a generic object will work, it is recommended to use a CreateJS Event instance. If a string is used, dispatchEvent will construct an Event instance if necessary with the specified type. This latter approach can be used to avoid event object instantiation for non-bubbling events that may not have any listeners.
-
[bubbles]
Boolean optionalSpecifies the
bubbles
value when a string was passed to eventObj. -
[cancelable]
Boolean optionalSpecifies the
cancelable
value when a string was passed to eventObj.
Returns:
Returns false if preventDefault()
was called on a cancelable event, true otherwise.
getItem
-
value
Look up a LoadItem using either the "id" or "src" that was specified when loading it. Note that if no "id" was
supplied with the load item, the ID will be the "src", including a path
property defined by a manifest. The
basePath
will not be part of the ID.
Parameters:
-
value
StringThe
id
orsrc
of the load item.
Returns:
The load item that was initially requested using loadFile
or loadManifest. This object is also returned via the fileload
event as the item
parameter.
getItems
-
loaded
Generate an list of items loaded by this queue.
Parameters:
-
loaded
BooleanDetermines if only items that have been loaded should be returned. If false, in-progress and failed load items will also be included.
getLoadedItems
()
Array
Get any items loaded internally by the loader. The enables loaders such as ManifestLoader to expose items it loads internally.
Returns:
A list of the items loaded by the loader.
getResult
-
value
-
[rawResult=false]
Look up a loaded result using either the "id" or "src" that was specified when loading it. Note that if no "id"
was supplied with the load item, the ID will be the "src", including a path
property defined by a manifest. The
basePath
will not be part of the ID.
Parameters:
Returns:
A result object containing the content that was loaded, such as:
- An image tag (<image />) for images
- A script tag for JavaScript (<script />). Note that scripts are automatically added to the HTML DOM.
- A style tag for CSS (<style /> or <link >)
- Raw text for TEXT
- A formatted JavaScript object defined by JSON
- An XML document
- A binary arraybuffer loaded by XHR
- An audio tag (<audio >) for HTML audio. Note that it is recommended to use SoundJS APIs to play loaded audio. Specifically, audio loaded by Flash and WebAudio will return a loader object using this method which can not be used to play audio back.
getTag
()
Object
Return the tag
this object creates or uses for loading.
Returns:
The tag instance
handleEvent
-
event
Handle events from internal requests. By default, loaders will handle, and redispatch the necessary events, but this method can be overridden for custom behaviours.
Parameters:
-
event
EventThe event that the internal request dispatches.
hasEventListener
-
type
Indicates whether there is at least one listener for the specified event type.
Parameters:
-
type
StringThe string type of the event.
Returns:
Returns true if there is at least one listener for the specified event.
init
-
preferXHR
-
basePath
-
crossOrigin
An internal initialization method, which is used for initial set up, but also to reset the LoadQueue.
installPlugin
-
plugin
Register a plugin. Plugins can map to load types (sound, image, etc), or specific extensions (png, mp3, etc). Currently, only one plugin can exist per type/extension.
When a plugin is installed, a getPreloadHandlers()
method will be called on it. For more information
on this method, check out the getPreloadHandlers method in the
SamplePlugin class.
Before a file is loaded, a matching plugin has an opportunity to modify the load. If a callback
is returned
from the getPreloadHandlers method, it will be invoked first, and its
result may cancel or modify the item. The callback method can also return a completeHandler
to be fired when
the file is loaded, or a tag
object, which will manage the actual download. For more information on these
methods, check out the preloadHandler and fileLoadHandler
methods on the SamplePlugin.
Parameters:
-
plugin
FunctionThe plugin class to install.
load
()
Start a LoadQueue that was created, but not automatically started.
loadFile
-
file
-
[loadNow=true]
-
[basePath]
Load a single file. To add multiple files at once, use the loadManifest method.
Files are always appended to the current queue, so this method can be used multiple times to add files. To clear the queue first, use the AbstractLoader/close method.
Parameters:
-
file
LoadItem | Object | String -
[loadNow=true]
Boolean optionalKick off an immediate load (true) or wait for a load call (false). The default value is true. If the queue is paused using setPaused, and the value is
true
, the queue will resume automatically. -
[basePath]
String optionalA base path that will be prepended to each file. The basePath argument overrides the path specified in the constructor. Note that if you load a manifest using a file of type MANIFEST, its files will NOT use the basePath parameter. The basePath parameter is deprecated. This parameter will be removed in a future version. Please either use the
basePath
parameter in the LoadQueue constructor, or apath
property in a manifest definition.
loadManifest
-
manifest
-
[loadNow=true]
-
[basePath]
Load an array of files. To load a single file, use the loadFile method. The files in the manifest are requested in the same order, but may complete in a different order if the max connections are set above 1 using setMaxConnections. Scripts will load in the right order as long as LoadQueue/maintainScriptOrder is true (which is default).
Files are always appended to the current queue, so this method can be used multiple times to add files. To clear the queue first, use the AbstractLoader/close method.
Parameters:
-
manifest
Array | String | ObjectAn list of files to load. The loadManifest call supports four types of manifests:
- A string path, which points to a manifest file, which is a JSON file that contains a "manifest" property, which defines the list of files to load, and can optionally contain a "path" property, which will be prepended to each file in the list.
- An object which defines a "src", which is a JSON or JSONP file. A "callback" can be defined for JSONP file. The JSON/JSONP file should contain a "manifest" property, which defines the list of files to load, and can optionally contain a "path" property, which will be prepended to each file in the list.
- An object which contains a "manifest" property, which defines the list of files to load, and can optionally contain a "path" property, which will be prepended to each file in the list.
- An Array of files to load.
Each "file" in a manifest can be either:
-
[loadNow=true]
Boolean optionalKick off an immediate load (true) or wait for a load call (false). The default value is true. If the queue is paused using setPaused and this value is
true
, the queue will resume automatically. -
[basePath]
String optionalA base path that will be prepended to each file. The basePath argument overrides the path specified in the constructor. Note that if you load a manifest using a file of type LoadQueue/MANIFEST:property, its files will NOT use the basePath parameter. The basePath parameter is deprecated. This parameter will be removed in a future version. Please either use the
basePath
parameter in the LoadQueue constructor, or apath
property in a manifest definition.
off
-
type
-
listener
-
[useCapture]
A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the .on method.
IMPORTANT: To remove a listener added with on
, you must pass in the returned wrapper function as the listener. See
on for an example.
on
-
type
-
listener
-
[scope]
-
[once=false]
-
[data]
-
[useCapture=false]
A shortcut method for using addEventListener that makes it easier to specify an execution scope, have a listener only run once, associate arbitrary data with the listener, and remove the listener.
This method works by creating an anonymous wrapper function and subscribing it with addEventListener.
The wrapper function is returned for use with removeEventListener
(or off
).
IMPORTANT: To remove a listener added with on
, you must pass in the returned wrapper function as the listener, or use
remove. Likewise, each time you call on
a NEW wrapper function is subscribed, so multiple calls
to on
with the same params will create multiple listeners.
Example
var listener = myBtn.on("click", handleClick, null, false, {count:3});
function handleClick(evt, data) {
data.count -= 1;
console.log(this == myBtn); // true - scope defaults to the dispatcher
if (data.count == 0) {
alert("clicked 3 times!");
myBtn.off("click", listener);
// alternately: evt.remove();
}
}
Parameters:
-
type
StringThe string type of the event.
-
listener
Function | ObjectAn object with a handleEvent method, or a function that will be called when the event is dispatched.
-
[scope]
Object optionalThe scope to execute the listener in. Defaults to the dispatcher/currentTarget for function listeners, and to the listener itself for object listeners (ie. using handleEvent).
-
[once=false]
Boolean optionalIf true, the listener will remove itself after the first time it is triggered.
-
[data]
optionalArbitrary data that will be included as the second parameter when the listener is called.
-
[useCapture=false]
Boolean optionalFor events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
Returns:
Returns the anonymous function that was created and assigned as the listener. This is needed to remove the listener later using .removeEventListener.
registerLoader
-
loader
Register a custom loaders class. New loaders are given precedence over loaders added earlier and default loaders. It is recommended that loaders extend AbstractLoader. Loaders can only be added once, and will be prepended to the list of available loaders.
Parameters:
-
loader
Function | AbstractLoaderThe AbstractLoader class to add.
remove
-
idsOrUrls
Stops an item from being loaded, and removes it from the queue. If nothing is passed, all items are removed. This also removes internal references to loaded item(s).
Example
queue.loadManifest([
{src:"test.png", id:"png"},
{src:"test.jpg", id:"jpg"},
{src:"test.mp3", id:"mp3"}
]);
queue.remove("png"); // Single item by ID
queue.remove("png", "test.jpg"); // Items as arguments. Mixed id and src.
queue.remove(["test.png", "jpg"]); // Items in an Array. Mixed id and src.
removeAll
()
Stops all queued and loading items, and clears the queue. This also removes all internal references to loaded content, and allows the queue to be used again.
removeAllEventListeners
-
[type]
Removes all listeners for the specified type, or all listeners of all types.
Example
// Remove all listeners
displayObject.removeAllEventListeners();
// Remove all click listeners
displayObject.removeAllEventListeners("click");
Parameters:
-
[type]
String optionalThe string type of the event. If omitted, all listeners for all types will be removed.
removeEventListener
-
type
-
listener
-
[useCapture]
Removes the specified event listener.
Important Note: that you must pass the exact function reference used when the event was added. If a proxy function, or function closure is used as the callback, the proxy/closure reference must be used - a new proxy or closure will not work.
Example
displayObject.removeEventListener("click", handleClick);
reset
()
setMaxConnections
-
value
Set the maximum number of concurrent connections. Note that browsers and servers may have a built-in maximum
number of open connections, so any additional connections may remain in a pending state until the browser
opens the connection. When loading scripts using tags, and when maintainScriptOrder
is true
, only one script is loaded at a time due to browser limitations.
Example
var queue = new createjs.LoadQueue();
queue.setMaxConnections(10); // Allow 10 concurrent loads
Parameters:
-
value
NumberThe number of concurrent loads to allow. By default, only a single connection per LoadQueue is open at any time.
setPaused
-
value
Pause or resume the current load. Active loads will not be cancelled, but the next items in the queue will not be processed when active loads complete. LoadQueues are not paused by default.
Note that if new items are added to the queue using loadFile or
loadManifest, a paused queue will be resumed, unless the loadNow
argument is false
.
Parameters:
-
value
BooleanWhether the queue should be paused or not.
setPreferXHR
-
value
Change the PreferXHR:property value. Note that if this is set to true
, it may
fail, or be ignored depending on the browser's capabilities and the load type.
Parameters:
-
value
Boolean
Returns:
The value of PreferXHR that was successfully set.
unregisterLoader
-
loader
Remove a custom loader added using RegisterLoader. Only custom loaders can be unregistered, the default loaders will always be available.
Parameters:
-
loader
Function | AbstractLoaderThe AbstractLoader class to remove
willTrigger
-
type
Indicates whether there is at least one listener for the specified event type on this object or any of its ancestors (parent, parent's parent, etc). A return value of true indicates that if a bubbling event of the specified type is dispatched from this object, it will trigger at least one listener.
This is similar to hasEventListener, but it searches the entire event flow for a listener, not just this object.
Parameters:
-
type
StringThe string type of the event.
Returns:
Returns true
if there is at least one listener for the specified event.
Properties
_availableLoaders
Array
private
An internal list of all the default Loaders that are included with PreloadJS. Before an item is loaded, the available loader list is iterated, in the order they are included, and as soon as a loader indicates it can handle the content, it will be selected. The default loader, (TextLoader is last in the list, so it will be used if no other match is found. Typically, loaders will match based on the LoadItem/type, which is automatically determined using the file extension of the src.
Loaders can be removed from PreloadJS by simply not including them.
Custom loaders installed using RegisterLoader will be prepended to this list so that they are checked first.
_basePath
String
private
A path that will be prepended on to the item's src. The
_basePath
property will only be used if an item's source is relative, and does not include a protocol such
as http://
, or a relative path such as ../
.
_crossOrigin
String
private
An optional flag to set on images that are loaded using PreloadJS, which enables CORS support. Images loaded cross-domain by servers that support CORS require the crossOrigin flag to be loaded and interacted with by a canvas. When loading locally, or with a server with no CORS support, this flag can cause other security issues, so it is recommended to only set it if you are sure the server supports it. Currently, supported values are "" and "Anonymous".
Default: ""
_currentlyLoadingScript
Boolean
private
Determines if there is currently a script loading. This helps ensure that only a single script loads at once when using a script tag to do preloading.
_defaultLoaderLength
Number
private
The number of built in loaders, so they can't be removed by {{#crossLink "unregisterLoader"}}{{/crossLink}.
_extensionCallbacks
Null
private
An object hash of callbacks that are fired for each file extension before the file is loaded, giving plugins the ability to override properties of the load. Please see the installPlugin method for more information.
_item
LoadItem | Object
private
The LoadItem this loader represents. Note that this is null in a LoadQueue, but will be available on loaders such as XMLLoader and ImageLoader.
_lastProgress
Number
private
The last progress amount. This is used to suppress duplicate progress events.
_loadedRawResults
Object
private
An object hash of un-parsed loaded items, indexed by the ID of the LoadItem.
_loadedScripts
Array
private
A list of scripts that have been loaded. Items are added to this list as null
when they are
requested, contain the loaded item if it has completed, but not been dispatched to the user, and true
once they are complete and have been dispatched.
_loadItems
Null
protected
A list of items that loaders load behind the scenes. This does not include the main item the loader is responsible for loading. Examples of loaders that have sub-items include the SpriteSheetLoader and ManifestLoader.
_loadItemsById
Object
private
An object hash of items that have finished downloading, indexed by the LoadItem id.
_loadItemsBySrc
Object
private
An object hash of items that have finished downloading, indexed by LoadItem source.
_loadQueue
Array
private
An array containing the queued items that have not yet started downloading.
_loadQueueBackup
Array
private
An array containing downloads that have not completed, so that the LoadQueue can be properly reset.
_loadStartWasDispatched
Boolean
private
Determines if the loadStart event was dispatched already. This event is only fired one time, when the first file is requested.
Default: false
_maxConnections
Number
private
The number of maximum open connections that a loadQueue tries to maintain. Please see setMaxConnections for more information.
Default: 1
_numItems
Number
private
The number of items that have been requested. This helps manage an overall progress without knowing how large the files are before they are downloaded. This does not include items inside of loaders such as the ManifestLoader.
Default: 0
_numItemsLoaded
Number
private
The number of items that have completed loaded. This helps manage an overall progress without knowing how large the files are before they are downloaded.
Default: 0
_preferXHR
Boolean
private
Whether the loader will try and load content using XHR (true) or HTML tags (false).
_rawResult
Object | String
private
The loaded result before it is formatted. The rawResult is accessed using the GetResult
method, and passing true
.
_result
Object | String
private
The loaded result after it is formatted by an optional ResultFormatter. For items that are not formatted, this will be the same as the _rawResult:property. The result is accessed using the GetResult method.
_scriptOrder
Array
private
A list of scripts in the order they were requested. This helps ensure that scripts are "completed" in the right order.
_tag
Object
private
An HTML tag (or similar) that a loader may use to load HTML content, such as images, scripts, etc.
_typeCallbacks
Object
private
An object hash of callbacks that are fired for each file type before the file is loaded, giving plugins the ability to override properties of the load. Please see the installPlugin method for more information.
canceled
Boolean
readonly
Determine if the loader was canceled. Canceled loads will not fire complete events. Note that this property is readonly, so LoadQueue queues should be closed using close instead.
Default: false
loaded
Boolean
If the loader has completed loading. This provides a quick check, but also ensures that the different approaches
used for loading do not pile up resulting in more than one complete
Event.
Default: false
maintainScriptOrder
Boolean
Ensure loaded scripts "complete" in the order they are specified. Loaded scripts are added to the document head
once they are loaded. Scripts loaded via tags will load one-at-a-time when this property is true
, whereas
scripts loaded using XHR can load in any order, but will "finish" and be added to the document in the order
specified.
Any items can be set to load in order by setting the MaintainOrder:property
property on the load item, or by ensuring that only one connection can be open at a time using
setMaxConnections. Note that when the maintainScriptOrder
property
is set to true
, scripts items are automatically set to maintainOrder=true
, and changing the
maintainScriptOrder
to false
during a load will not change items already in a queue.
Example
var queue = new createjs.LoadQueue();
queue.setMaxConnections(3); // Set a higher number to load multiple items at once
queue.maintainScriptOrder = true; // Ensure scripts are loaded in order
queue.loadManifest([
"script1.js",
"script2.js",
"image.png", // Load any time
{src: "image2.png", maintainOrder: true} // Will wait for script2.js
"image3.png",
"script3.js" // Will wait for image2.png before loading (or completing when loading with XHR)
]);
Default: true
next
LoadQueue
The next preload queue to process when this one is complete. If an error is thrown in the current queue, and
stopOnError is true
, the next queue will not be processed.
Default: null
progress
Number
The current load progress (percentage) for this item. This will be a number between 0 and 1.
Example
var queue = new createjs.LoadQueue();
queue.loadFile("largeImage.png");
queue.on("progress", function() {
console.log("Progress:", queue.progress, event.progress);
});
Default: 0
resultFormatter
Function
A formatter function that converts the loaded raw result into the final result. For example, the JSONLoader converts a string of text into a JavaScript object. Not all loaders have a resultFormatter, and this property can be overridden to provide custom formatting.
Optionally, a resultFormatter can return a callback function in cases where the formatting needs to be asynchronous, such as creating a new image. The callback function is passed 2 parameters, which are callbacks to handle success and error conditions in the resultFormatter. Note that the resultFormatter method is called in the current scope, as well as the success and error callbacks.
Example asynchronous resultFormatter
function _formatResult(loader) {
return function(success, error) {
if (errorCondition) { error(errorDetailEvent); }
success(result);
}
}
Default: null
stopOnError
Boolean
Determines if the LoadQueue will stop processing the current queue when an error is encountered.
Default: false
type
String
The type of item this loader will load. See AbstractLoader for a full list of supported types.
Events
complete
The Event that is fired when the entire queue has been loaded.
error
The ErrorEvent that is fired when the loader encounters an error. If the error was encountered by a file, the event will contain the item that caused the error. Prior to version 0.6.0, this was just a regular Event.
fileerror
The Event that is fired when the loader encounters an internal file load error. This enables loaders to maintain internal queues, and surface file load errors.
fileload
This event is fired when an individual file has loaded, and been processed.
Event Payload:
-
target
ObjectThe object that dispatched the event.
-
type
StringThe event type.
-
item
ObjectThe file item which was specified in the loadFile or loadManifest call. If only a string path or tag was specified, the object will contain that value as a
src
property. -
result
ObjectThe HTML tag or parsed result of the loaded item.
-
rawResult
ObjectThe unprocessed result, usually the raw text or binary data before it is converted to a usable object.
fileprogress
This ProgressEvent that is fired when an an individual file's progress changes.
filestart
This event is fired when an individual file starts to load.
Event Payload:
-
target
ObjectThe object that dispatched the event.
-
type
StringThe event type.
-
item
ObjectThe file item which was specified in the loadFile or loadManifest call. If only a string path or tag was specified, the object will contain that value as a property.
initialize
private
Although it extends AbstractLoader, the initialize
event is never fired from
a LoadQueue instance.
loadstart
The Event that is fired when a load starts.
progress
The ProgressEvent that is fired when the overall progress changes. Prior to version 0.6.0, this was just a regular Event.