XHRRequest Class
A preloader that loads items using XHR requests, usually XMLHttpRequest. However XDomainRequests will be used for cross-domain requests if possible, and older versions of IE fall back on to ActiveX objects when necessary. XHR requests load the content as text or binary data, provide progress and consistent completion events, and can be canceled during load. Note that XHR is not supported in IE 6 or earlier, and is not recommended for cross-domain loading.
Constructor
Item Index
Methods
- _checkError
 - _clean
 - _createRequest
 - _createTag
 - _createXHR
 - _dispatchEvent
 - _getResponse
 - _handleError
 - _handleLoad
 - _handleLoadStart
 - _handleProgress
 - _handleReadyStateChange
 - _handleTimeout
 - _isCanceled
 - _resultFormatSuccess
 - _sendComplete
 - _sendError
 - _sendLoadStart
 - _sendProgress
 - addEventListener
 - cancel
 - destroy
 - dispatchEvent
 - getAllResponseHeaders
 - getItem
 - getLoadedItems
 - getResponseHeader
 - getResult
 - getTag
 - handleAbort
 - handleEvent
 - hasEventListener
 - load
 - off
 - on
 - removeAllEventListeners
 - removeEventListener
 - setTag
 - toString
 - willTrigger
 
Properties
Methods
_checkError
    
        ()
    
    
        
            Error
        
    
    
    
        private
    
    
    
    
    
    
    Determine if there is an error in the current load. Currently this checks the status of the request for problem codes, and not actual response content:
- Status codes between 400 and 599 (HTTP error range)
 - A status of 0, but only when the application is running on a server. If the application is running
    on 
file:, then it may incorrectly treat an error on local (or embedded applications) as a successful load. 
Returns:
An error with the status code in the message argument.
_clean
    
        ()
    
    
    
    
        private
    
    
    
    
    
    
    A request has completed (or failed or canceled), and needs to be disposed.
_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:
- 
                    
                        
srcStringThe tag source
 
Returns:
The tag that was created
_createXHR
    
        - 
                    
                        
item 
Create an XHR request. Depending on a number of factors, we get totally different results.
- Some browsers get an 
XDomainRequestwhen loading cross-domain. - XMLHttpRequest are created when available.
 - ActiveX.XMLHTTP objects are used in older IE browsers.
 - Text requests override the mime type if possible
 - Origin headers are sent for crossdomain requests in some browsers.
 - Binary loads set the response type to "arraybuffer"
 
Parameters:
- 
                    
                        
itemObjectThe requested item that is being loaded.
 
Returns:
If an XHR request or equivalent was successfully created.
_dispatchEvent
    
        - 
                    
                        
eventObj - 
                    
                        
eventPhase 
_getResponse
    
        ()
    
    
    
    
        private
    
    
    
    
    
    
    Validate the response. Different browsers have different approaches, some of which throw errors when accessed
in other browsers. If there is no response, the _response property will remain null.
_handleError
    
        - 
                    
                        
event 
The XHR request has reported an error event.
Parameters:
- 
                    
                        
eventObjectThe XHR error event.
 
_handleLoad
    
        - 
                    
                        
event 
The XHR request has completed. This is called by the XHR request directly, or by a readyStateChange that has
request.readyState == 4. Only the first call to this method will be processed.
Note that This method uses _checkError to determine if the server has returned an error code.
Parameters:
- 
                    
                        
eventObjectThe XHR load event.
 
_handleLoadStart
    
        - 
                    
                        
event 
The XHR request has reported a load start.
Parameters:
- 
                    
                        
eventObjectThe XHR loadStart event.
 
_handleProgress
    
        - 
                    
                        
event 
The XHR request has reported progress.
Parameters:
- 
                    
                        
eventObjectThe XHR progress event.
 
_handleReadyStateChange
    
        - 
                    
                        
event 
The XHR request has reported a readyState change. Note that older browsers (IE 7 & 8) do not provide an onload event, so we must monitor the readyStateChange to determine if the file is loaded.
Parameters:
- 
                    
                        
eventObjectThe XHR readyStateChange event.
 
_handleTimeout
    
        - 
                    
                        
[event] 
The XHR request has timed out. This is called by the XHR request directly, or via a setTimeout
callback.
Parameters:
- 
                    
                        
[event]Object optionalThe XHR timeout event. This is occasionally null when called by the backup setTimeout.
 
_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.
_resultFormatSuccess
    
        - 
                    
                        
result 
The "success" callback passed to AbstractLoader/resultFormatter asynchronous functions.
Parameters:
- 
                    
                        
resultObjectThe formatted result
 
_sendError
    
        - 
                    
                        
event 
Parameters:
- 
                    
                        
eventErrorEventThe event object containing specific error properties.
 
_sendLoadStart
    
        ()
    
    
    
    
        protected
    
    
    
    
    
    
    
    
    
    
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:
- 
                    
                        
typeStringThe string type of the event.
 - 
                    
                        
listenerFunction | 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.
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:
- 
                    
                        
eventObjObject | 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
bubblesvalue when a string was passed to eventObj. - 
                    
                        
[cancelable]Boolean optionalSpecifies the
cancelablevalue when a string was passed to eventObj. 
Returns:
Returns false if preventDefault() was called on a cancelable event, true otherwise.
getAllResponseHeaders
    
        ()
    
    
        
            String
        
    
    
    
    
    
    
    
    
    Get all the response headers from the XmlHttpRequest.
From the docs: Return all the HTTP headers, excluding headers that are a case-insensitive match for Set-Cookie or Set-Cookie2, as a single string, with each header line separated by a U+000D CR U+000A LF pair, excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE pair.
Returns:
getItem
    
        ()
    
    
        
            Object
        
    
    
    
    
    
    
    
    
    Get a reference to the manifest item that is loaded by this loader. In some cases this will be the value that was passed into LoadQueue using loadFile or loadManifest. However if only a String path was passed in, then it will be a LoadItem.
Returns:
The manifest item that this loader is responsible for loading.
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.
getResponseHeader
    
        - 
                    
                        
header 
Get a specific response header from the XmlHttpRequest.
From the docs: Returns the header field value from the response of which the field name matches header, unless the field name is Set-Cookie or Set-Cookie2.
Parameters:
- 
                    
                        
headerStringThe header name to retrieve.
 
Returns:
getResult
    
        - 
                    
                        
[raw=false] 
Look up the loaded result.
Parameters:
- 
                    
                        
[raw=false]Boolean optionalReturn a raw result instead of a formatted result. This applies to content loaded via XHR such as scripts, XML, CSS, and Images. If there is no raw result, the formatted result will be returned instead.
 
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 loaded with tags may be added to the HTML head.
 - A style tag for CSS (<style />)
 - Raw text for TEXT
 - A formatted JavaScript object defined by JSON
 - An XML document
 - An binary arraybuffer loaded by XHR
 
getTag
    
        ()
    
    
        
            Object
        
    
    
    
    
    
    
    
    
    Return the tag this object creates or uses for loading.
Returns:
The tag instance
handleAbort
    
        - 
                    
                        
event 
The XHR request has reported an abort event.
Parameters:
- 
                    
                        
eventObjectThe XHR abort event.
 
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:
- 
                    
                        
eventEventThe event that the internal request dispatches.
 
hasEventListener
    
        - 
                    
                        
type 
Indicates whether there is at least one listener for the specified event type.
Parameters:
- 
                    
                        
typeStringThe string type of the event.
 
Returns:
Returns true if there is at least one listener for the specified event.
load
    
        ()
    
    
    
    
    
    
    
    
    
    Begin loading the item. This method is required when using a loader by itself.
Example
 var queue = new createjs.LoadQueue();
 queue.on("complete", handleComplete);
 queue.loadManifest(fileArray, false); // Note the 2nd argument that tells the queue not to start loading yet
 queue.load();
    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:
- 
                    
                        
typeStringThe string type of the event.
 - 
                    
                        
listenerFunction | 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.
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);
    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:
- 
                    
                        
typeStringThe string type of the event.
 
Returns:
Returns true if there is at least one listener for the specified event.
Properties
_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.
_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.
_loadTimeout
    Number
    
    
        private
    
    
    
    
    
    A manual load timeout that is used for browsers that do not support the onTimeout event on XHR (XHR level 1, typically IE9).
_preferXHR
    Boolean
    
    
        private
    
    
    
    
    
    Whether the loader will try and load content using XHR (true) or HTML tags (false).
_rawResponse
    String | Object
    
    
        private
    
    
    
    
    
    The response of the loaded file before it is modified. In most cases, content is converted from raw text to
an HTML tag or a formatted object which is set to the result property, but the developer may still
want to access the raw content as it was loaded.
_rawResult
    Object | String
    
    
        private
    
    
    
    
    
    The loaded result before it is formatted. The rawResult is accessed using the GetResult
method, and passing true.
_request
    XMLHttpRequest | XDomainRequest | ActiveX.XMLHTTP
    
    
        private
    
    
    
    
    
    A reference to the XHR request used to load the content.
_response
    Mixed
    
    
        private
    
    
    
    
    
    The response of a loaded file. This is set because it is expensive to look up constantly. This property will be null until the file is loaded.
_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.
_tag
    Object
    
    
        private
    
    
    
    
    
    An HTML tag (or similar) that a loader may use to load HTML content, such as images, scripts, etc.
_xhrLevel
    Number
    
    
        private
    
    
    
    
    
    The browser's XHR (XMLHTTPRequest) version. Supported versions are 1 and 2. There is no official way to detect the version, so we use capabilities to make a best guess.
Default: 1
ACTIVEX_VERSIONS
    Array
    
    
        private
    
    
    
    
    
    A list of XMLHTTP object IDs to try when building an ActiveX object for XHR requests in earlier versions of IE.
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
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
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
    
    
    
    
    
    
    The Event that is fired when a loader internally loads a file. This enables loaders such as ManifestLoader to maintain internal LoadQueues and notify when they have loaded a file. The LoadQueue class dispatches a slightly different fileload event.
Event Payload:
- 
                    
                        
targetObjectThe object that dispatched the event.
 - 
                    
                        
typeStringThe event type ("fileload")
 - 
                    
                        
itemObjectThe 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
srcproperty. - 
                    
                        
resultObjectThe HTML tag or parsed result of the loaded item.
 - 
                    
                        
rawResultObjectThe unprocessed result, usually the raw text or binary data before it is converted to a usable object.
 
initialize
    
    
    
    
    
    
    The Event that is fired after the internal request is created, but before a load. This allows updates to the loader for specific loading needs, such as binary or XHR image loading.
Event Payload:
- 
                    
                        
targetObjectThe object that dispatched the event.
 - 
                    
                        
typeStringThe event type ("initialize")
 - 
                    
                        
loaderAbstractLoaderThe loader that has been initialized.
 
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.