API Documentation for: 0.4.1
Show:

XHRLoader Class

Extends AbstractLoader
Defined in: XHRLoader:40
Module: PreloadJS

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

XHRLoader

(
  • item
  • [crossOrigin]
)

Defined in XHRLoader:40

Parameters:

  • item Object

    The object that defines the file to load. Please see the loadFile for an overview of supported file properties.

  • [crossOrigin] String optional

    An optional flag to support images loaded from a CORS-enabled server. Please see _crossOrigin for more info.

Methods

_checkError

() Boolean private

Defined in _checkError:348

Determine if there is an error in the current load. This checks the status of the request for problem codes. Note that this does not check for an actual response. Currently, it only checks for 404 or 0 error code.

Returns:

Boolean:

If the request status returns an error code.

_clean

() private

Defined in _clean:481

A request has completed (or failed or canceled), and needs to be disposed.

_createXHR

(
  • item
)
Boolean private

Defined in _createXHR:401

Create an XHR request. Depending on a number of factors, we get totally different results.

  1. Some browsers get an XDomainRequest when loading cross-domain.
  2. XMLHttpRequest are created when available.
  3. ActiveX.XMLHTTP objects are used in older IE browsers.
  4. Text requests override the mime type if possible
  5. Origin headers are sent for crossdomain requests in some browsers.
  6. Binary loads set the response type to "arraybuffer"

Parameters:

  • item Object

    The requested item that is being loaded.

Returns:

Boolean:

If an XHR request or equivalent was successfully created.

_dispatchEvent

(
  • eventObj
  • eventPhase
)
protected

Parameters:

_formatQueryString

(
  • data
  • [query]
)
private

Formats an object into a query string for either a POST or GET request.

Parameters:

  • data Object

    The data to convert to a query string.

  • [query] Array optional

    Existing name/value pairs to append on to this query.

_generateTag

() Boolean private

Defined in _generateTag:500

Generate a tag for items that can be represented as tags. For example, IMAGE, SCRIPT, and LINK. This also handles XML and SVG objects.

Returns:

Boolean:

If a tag was generated and is ready for instantiation. If it still needs processing, this method returns false.

_getResponse

() private

Defined in _getResponse:367

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
)
private

Defined in _handleError:279

The XHR request has reported an error event.

Parameters:

  • event Object

    The XHR error event.

_handleLoad

(
  • event
)
private

Defined in _handleLoad:305

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.

Parameters:

  • event Object

    The XHR load event.

_handleLoadStart

(
  • event
)
private

The XHR request has reported a load start.

Parameters:

  • event Object

    The XHR loadStart event.

_handleProgress

(
  • event
)
private

Defined in _handleProgress:238

The XHR request has reported progress.

Parameters:

  • event Object

    The XHR progress event.

_handleReadyStateChange

(
  • event
)
private

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:

  • event Object

    The XHR readyStateChange event.

_handleTagReady

() private

Defined in _handleTagReady:606

A generated tag is now ready for use.

_handleTimeout

(
  • [event]
)
private

Defined in _handleTimeout:331

The XHR request has timed out. This is called by the XHR request directly, or via a setTimeout callback.

Parameters:

  • [event] Object optional

    The 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:

Boolean:

If the loader has been canceled.

_isCrossDomain

(
  • item
)
Boolean private

Parameters:

  • item Object

    A load item with a src property

Returns:

Boolean:

If the load item is loading from a different domain than the current location.

_isLocal

(
  • item
)
Boolean private

Inherited from AbstractLoader: _isLocal:405

Parameters:

  • item Object

    A load item with a src property

Returns:

Boolean:

If the load item is loading from the "file:" protocol. Assume that the host must be local as well.

_parsePath

(
  • path
)
Array protected

Inherited from AbstractLoader: _parsePath:321

Parse a file URI using the AbstractLoader/PATH_PATTERN RegExp pattern.

Parameters:

  • path String

    The file path to parse.

Returns:

Array:

The matched path contents. Please see the PATH_PATTERN property for details on the return value. This will return null if it does not match.

_parseURI

(
  • path
)
Array protected

Inherited from AbstractLoader: _parseURI:308

Parse a file URI using the FILE_PATTERN RegExp pattern.

Parameters:

  • path String

    The file path to parse.

Returns:

Array:

The matched file contents. Please see the FILE_PATTERN property for details on the return value. This will return null if it does not match.

_parseXML

(
  • text
  • type
)
XML private

Defined in _parseXML:581

Parse XML using the DOM. This is required when preloading XML or SVG.

Parameters:

  • text String

    The raw text or XML that is loaded by XHR.

  • type String

    The mime type of the XML.

Returns:

XML:

An XML document.

_sendComplete

() protected

Dispatch a complete event. Please see the complete event for details on the event payload.

_sendError

(
  • event
)
protected

Inherited from AbstractLoader: _sendError:279

Dispatch an error event. Please see the error event for details on the event payload.

Parameters:

  • event Object

    The event object containing specific error properties.

_sendLoadStart

() protected

Dispatch a loadstart event. Please see the loadstart event for details on the event payload.

_sendProgress

(
  • value
)
protected

Dispatch a progress event. Please see the progress event for details on the event payload.

Parameters:

  • value Number | Object

    The progress of the loaded item, or an object containing loaded and total properties.

addEventListener

(
  • type
  • listener
  • [useCapture]
)
Function | Object

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 String

    The string type of the event.

  • listener Function | Object

    An object with a handleEvent method, or a function that will be called when the event is dispatched.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

Returns:

Function | Object:

Returns the listener for chaining or assignment.

buildPath

(
  • src
  • [data]
)
String

Inherited from AbstractLoader: buildPath:355

Available since 0.3.1

A utility method that builds a file path using a source and a data object, and formats it into a new path. All of the loaders in PreloadJS use this method to compile paths when loading.

Parameters:

  • src String

    The source path to add values to.

  • [data] Object optional

    Object used to append values to this request as a query string. Existing parameters on the path will be preserved.

Returns:

String:

A formatted string that contains the path and the supplied parameters.

close

()

Inherited from AbstractLoader: close:221

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.

dispatchEvent

(
  • eventObj
  • [target]
)
Boolean

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 | Event

    An 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 with the specified type.

  • [target] Object optional

    The object to use as the target property of the event object. This will default to the dispatching object. This parameter is deprecated and will be removed.

Returns:

Boolean:

Returns the value of eventObj.defaultPrevented.

getAllResponseHeaders

() String

Defined in getAllResponseHeaders:201

Available since 0.4.1

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:

getResponseHeader

(
  • header
)
String

Defined in getResponseHeader:220

Available since 0.4.1

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:

  • header String

    The header name to retrieve.

Returns:

getResult

(
  • [rawResult=false]
)
Object

Defined in getResult:125

Look up the loaded result.

Parameters:

  • [rawResult=false] Boolean optional

    Return 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:

Object:

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
Note that if a raw result is requested, but not found, the result will be returned instead.

handleAbort

(
  • event
)
private

Defined in handleAbort:266

The XHR request has reported an abort event.

Parameters:

  • event Object

    The XHR abort event.

hasEventListener

(
  • type
)
Boolean

Indicates whether there is at least one listener for the specified event type.

Parameters:

  • type String

    The string type of the event.

Returns:

Boolean:

Returns true if there is at least one listener for the specified event.

init

() private

Inherited from AbstractLoader: init:202

Initialize the loader. This is called by the constructor.

initialize

() protected

Initialization method.

load

()

Inherited from AbstractLoader: load:209

Begin loading the queued items. This method can be called when a LoadQueue is set up but not started immediately.

Example:

 var queue = new createjs.LoadQueue();
 queue.addEventListener("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]
)

Inherited from EventDispatcher: off:247

A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the .on method.

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    The listener function or object.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

on

(
  • type
  • listener
  • [scope]
  • [once=false]
  • [data]
  • [useCapture=false]
)
Function

Inherited from EventDispatcher: on:175

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 created anonymous function is returned for use with .removeEventListener (or .off).

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 String

    The string type of the event.

  • listener Function | Object

    An object with a handleEvent method, or a function that will be called when the event is dispatched.

  • [scope] Object optional

    The 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 optional

    If true, the listener will remove itself after the first time it is triggered.

  • [data] optional

    Arbitrary data that will be included as the second parameter when the listener is called.

  • [useCapture=false] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

Returns:

Function:

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 optional

    The 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);

Parameters:

  • type String

    The string type of the event.

  • listener Function | Object

    The listener function or object.

  • [useCapture] Boolean optional

    For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.

toString

() String

Inherited from EventDispatcher but overwritten in toString:418

Returns:

String:

a string representation of the instance.

willTrigger

(
  • type
)
Boolean

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 String

    The string type of the event.

Returns:

Boolean:

Returns true if there is at least one listener for the specified event.

Properties

_captureListeners

Object protected

_crossOrigin

String private

Defined in _crossOrigin:107

_item

Object private

Inherited from AbstractLoader: _item:109

The item this loader represents. Note that this is null in a LoadQueue, but will be available on loaders such as XHRLoader and TagLoader.

_listeners

Object protected

_loadTimeout

Number private

Defined in _loadTimeout:69

A manual load timeout that is used for browsers that do not support the onTimeout event on XHR (XHR level 1, typically IE9).

_rawResponse

String | Object private

Defined in _rawResponse:97

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.

_request

XMLHttpRequest | XDomainRequest | ActiveX.XMLHTTP private

Defined in _request:61

A reference to the XHR request used to load the content.

_response

Mixed private

Defined in _response:88

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.

_xhrLevel

Number private

Defined in _xhrLevel:78

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

canceled

Boolean

Inherited from AbstractLoader: canceled:82

Determine if the loader was canceled. Canceled loads will not fire complete events. Note that LoadQueue queues should be closed using close instead of setting this property.

Default: false

loaded

Boolean

Inherited from AbstractLoader: loaded:73

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

onComplete

Function deprecated

Inherited from AbstractLoader: onComplete:176

Deprecated: Use addEventListener and the "complete" event.

REMOVED. Use addEventListener and the complete event.

onError

Function deprecated

Inherited from AbstractLoader: onError:183

Deprecated: Use addEventListener and the "error" event.

REMOVED. Use addEventListener and the error event.

onLoadStart

Function deprecated

Inherited from AbstractLoader: onLoadStart:169

Deprecated: Use addEventListener and the "loadstart" event.

REMOVED. Use addEventListener and the loadstart event.

onProgress

Function deprecated

Inherited from AbstractLoader: onProgress:162

Deprecated: Use addEventListener and the "progress" event.

REMOVED. Use addEventListener and the progress event.

progress

Number

Inherited from AbstractLoader: progress:92

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

Events

complete

Inherited from AbstractLoader: complete:139

Available since 0.3.0

The event that is fired when the entire queue has been loaded.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type.

error

Inherited from AbstractLoader: error:147

Available since 0.3.0

The event 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. There may be additional properties such as the error reason on event objects.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type.

  • [item] Object optional

    The item that was being loaded that caused the error. The item 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.

  • [error] String optional

    The error object or text.

loadstart

Inherited from AbstractLoader: loadstart:131

Available since 0.3.1

The event that is fired when a load starts.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type.

progress

Inherited from AbstractLoader: progress:119

Available since 0.3.0

The event that is fired when the overall progress changes.

Event Payload:

  • target Object

    The object that dispatched the event.

  • type String

    The event type.

  • loaded Number

    The amount that has been loaded so far. Note that this is may just be a percentage of 1, since file sizes can not be determined before a load is kicked off, if at all.

  • total Number

    The total number of bytes. Note that this may just be 1.

  • progress Number

    The ratio that has been loaded between 0 and 1.