loader Class

Extends Pipeline

Module: cc

Loader for resource loading process. It's a singleton object.

Index

Properties
  • assetLoader Object The asset loader in cc.loader's pipeline, it's by default the first pipe.
  • md5Pipe Object The md5 pipe in cc.loader's pipeline, it could be absent if the project isn't build with md5 option.
  • downloader Object The downloader in cc.loader's pipeline, it's by default the second pipe.
  • loader Object The loader in cc.loader's pipeline, it's by default the third pipe.
Methods
  • getXMLHttpRequest Gets a new XMLHttpRequest instance.
  • addDownloadHandlers Add custom supported types handler or modify existing type handler for download process.
  • addLoadHandlers Add custom supported types handler or modify existing type handler for load process.
  • load Load resources with a progression callback and a complete callback.
  • loadRes Load resources from the "resources" folder inside the "assets" folder of your project.
    ...
  • loadResArray This method is like loadRes except that it accepts array of url.
  • loadResDir Load all assets in a folder inside the "assets/resources" folder of your project.
    ...
  • getRes Get resource data by id.
  • getDependsRecursively Get all resource dependencies of the loaded asset in an array, including itself.
  • release Release the content of an asset or an array of assets by uuid.
  • releaseAsset Release the asset by its object.
  • releaseRes Release the asset loaded by loadRes.
  • releaseResDir Release the all assets loaded by loadResDir.
  • releaseAll Resource all assets.
  • setAutoRelease according to whether the previous scene checked the "Auto Release Assets" option.
  • setAutoReleaseRecursively according to whether the previous scene checked the "Auto Release Assets" option.
  • isAutoRelease Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.
    ...
  • constructor Constructor, pass an array of pipes to construct a new Pipeline,...
  • insertPipe Insert a new pipe at the given index of the pipeline.
  • insertPipeAfter Insert a pipe to the end of an existing pipe.
  • appendPipe Add a new pipe at the end of the pipeline.
  • flowIn Let new items flow into the pipeline.
  • copyItemStates Copy the item states from one source item to all destination items.
  • getItem Returns an item in pipeline.
  • removeItem Removes an completed item in pipeline.
  • clear Clear the current pipeline, this function will clean up the items.

Details

Properties

assetLoader

The asset loader in cc.loader's pipeline, it's by default the first pipe. It's used to identify an asset's type, and determine how to download it.

meta description
Type Object
Defined in cocos2d/core/load-pipeline/CCLoader.js:102
md5Pipe

The md5 pipe in cc.loader's pipeline, it could be absent if the project isn't build with md5 option. It's used to modify the url to the real downloadable url with md5 suffix.

meta description
Type Object
Defined in cocos2d/core/load-pipeline/CCLoader.js:110
downloader

The downloader in cc.loader's pipeline, it's by default the second pipe. It's used to download files with several handlers: pure text, image, script, audio, font, uuid. You can add your own download function with addDownloadHandlers

meta description
Type Object
Defined in cocos2d/core/load-pipeline/CCLoader.js:118
loader

The loader in cc.loader's pipeline, it's by default the third pipe. It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid. You can add your own download function with addLoadHandlers

meta description
Type Object
Defined in cocos2d/core/load-pipeline/CCLoader.js:127

Methods

getXMLHttpRequest

Gets a new XMLHttpRequest instance.

meta description
Returns XMLHttpRequest
Defined in cocos2d/core/load-pipeline/CCLoader.js:157
addDownloadHandlers

Add custom supported types handler or modify existing type handler for download process.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:164
Parameters
  • extMap Object Custom supported types with corresponded handler
Examples
cc.loader.addDownloadHandlers({
     // This will match all url with `.scene` extension or all url with `scene` type
     'scene' : function (url, callback) {}
 });
addLoadHandlers

Add custom supported types handler or modify existing type handler for load process.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:178
Parameters
  • extMap Object Custom supported types with corresponded handler
Examples
cc.loader.addLoadHandlers({
     // This will match all url with `.scene` extension or all url with `scene` type
     'scene' : function (url, callback) {}
 });
load

Load resources with a progression callback and a complete callback. The progression callback is the same as Pipeline's onProgress The complete callback is almost the same as Pipeline's onComplete The only difference is when user pass a single url as resources, the complete callback will set its result directly as the second parameter.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:192
Parameters
  • resources String | String[] | Object Url list in an array
  • progressCallback Function Callback invoked when progression change
    • completedCount Number The number of the items that are already completed
    • totalCount Number The total number of the items
    • item Object The latest item which flow out the pipeline
  • completeCallback Function Callback invoked when all resources loaded
Examples
cc.loader.load('a.png', function (err, tex) {
    cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D));
});

cc.loader.load('http://example.com/a.png', function (err, tex) {
    cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D));
});

cc.loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) {
    cc.log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof cc.Texture2D));
});

cc.loader.load(['a.png', 'b.json'], function (errors, results) {
    if (errors) {
        for (var i = 0; i < errors.length; i++) {
            cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i]));
        }
    }
    var aTex = results.getContent('a.png');
    var bJsonObj = results.getContent('b.json');
});
loadRes

Load resources from the "resources" folder inside the "assets" folder of your project.

Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:425
Parameters
  • url String Url of the target resource.
                    The url is relative to the "resources" folder, extensions must be omitted.
    
  • type Function Only asset of type will be loaded if this argument is supplied.
  • progressCallback Function Callback invoked when progression change.
    • completedCount Number The number of the items that are already completed.
    • totalCount Number The total number of the items.
    • item Object The latest item which flow out the pipeline.
  • completeCallback Function Callback invoked when the resource loaded.
    • error Error The error info or null if loaded successfully.
    • resource Object The loaded resource if it can be found otherwise returns null.
Examples
// load the prefab (project/assets/resources/misc/character/cocos) from resources folder
cc.loader.loadRes('misc/character/cocos', function (err, prefab) {
    if (err) {
        cc.error(err.message || err);
        return;
    }
    cc.log('Result should be a prefab: ' + (prefab instanceof cc.Prefab));
});

// load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder
cc.loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) {
    if (err) {
        cc.error(err.message || err);
        return;
    }
    cc.log('Result should be a sprite frame: ' + (spriteFrame instanceof cc.SpriteFrame));
});
loadResArray

This method is like loadRes except that it accepts array of url.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:555
Parameters
  • urls String[] Array of URLs of the target resource.
                       The url is relative to the "resources" folder, extensions must be omitted.
    
  • type Function Only asset of type will be loaded if this argument is supplied.
  • progressCallback Function Callback invoked when progression change.
    • completedCount Number The number of the items that are already completed.
    • totalCount Number The total number of the items.
    • item Object The latest item which flow out the pipeline.
  • completeCallback Function A callback which is called when all assets have been loaded, or an error occurs.
    • error Error If one of the asset failed, the complete callback is immediately called
                                    with the error. If all assets are loaded successfully, error will be null.
      
    • assets Asset[] | Array An array of all loaded assets.
                                                If nothing to load, assets will be an empty array.
      
Examples
// load the SpriteFrames from resources folder
var spriteFrames;
var urls = ['misc/characters/character_01', 'misc/weapons/weapons_01'];
cc.loader.loadResArray(urls, cc.SpriteFrame, function (err, assets) {
    if (err) {
        cc.error(err);
        return;
    }
    spriteFrames = assets;
    // ...
});
loadResDir

Load all assets in a folder inside the "assets/resources" folder of your project.

Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:622
Parameters
  • url String Url of the target folder.
                    The url is relative to the "resources" folder, extensions must be omitted.
    
  • type Function Only asset of type will be loaded if this argument is supplied.
  • progressCallback Function Callback invoked when progression change.
    • completedCount Number The number of the items that are already completed.
    • totalCount Number The total number of the items.
    • item Object The latest item which flow out the pipeline.
  • completeCallback Function A callback which is called when all assets have been loaded, or an error occurs.
    • error Error If one of the asset failed, the complete callback is immediately called
                                    with the error. If all assets are loaded successfully, error will be null.
      
    • assets Asset[] | Array An array of all loaded assets.
                                        If nothing to load, assets will be an empty array.
      
    • urls String[] An array that lists all the URLs of loaded assets.
Examples
// load the texture (resources/imgs/cocos.png) and the corresponding sprite frame
cc.loader.loadResDir('imgs/cocos', function (err, assets) {
    if (err) {
        cc.error(err);
        return;
    }
    var texture = assets[0];
    var spriteFrame = assets[1];
});

// load all textures in "resources/imgs/"
cc.loader.loadResDir('imgs', cc.Texture2D, function (err, textures) {
    var texture1 = textures[0];
    var texture2 = textures[1];
});

// load all JSONs in "resources/data/"
cc.loader.loadResDir('data', function (err, objects, urls) {
    var data = objects[0];
    var url = urls[0];
});
getRes

Get resource data by id.
When you load resources with load or loadRes, the url will be the unique identity of the resource. After loaded, you can acquire them by passing the url to this API.

meta description
Returns Any
Defined in cocos2d/core/load-pipeline/CCLoader.js:693
Parameters
  • url String
  • type Function Only asset of type will be returned if this argument is supplied.
getDependsRecursively

Get all resource dependencies of the loaded asset in an array, including itself. The owner parameter accept the following types: 1. The asset itself; 2. The resource url; 3. The asset's uuid.
The returned array stores the dependencies with their uuids, after retrieve dependencies, you can release them, access dependent assets by passing the uuid to getRes, or other stuffs you want.
For release all dependencies of an asset, please refer to release Here is some examples:

meta description
Returns Array
Defined in cocos2d/core/load-pipeline/CCLoader.js:730
Parameters
Examples
// Release all dependencies of a loaded prefab
var deps = cc.loader.getDependsRecursively(prefab);
cc.loader.release(deps);
// Retrieve all dependent textures
var deps = cc.loader.getDependsRecursively('prefabs/sample');
var textures = [];
for (var i = 0; i < deps.length; ++i) {
    var item = cc.loader.getRes(deps[i]);
    if (item instanceof cc.Texture2D) {
        textures.push(item);
    }
}
release

Release the content of an asset or an array of assets by uuid. Start from v1.3, this method will not only remove the cache of the asset in loader, but also clean up its content. For example, if you release a texture, the texture asset and its gl texture data will be freed up. In complexe project, you can use this function with getDependsRecursively to free up memory in critical circumstances. Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black and report gl errors. If you only want to remove the cache of an asset, please use Pipeline/removeItem:method

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:773
Parameters
Examples
// Release a texture which is no longer need
cc.loader.release(texture);
// Release all dependencies of a loaded prefab
var deps = cc.loader.getDependsRecursively('prefabs/sample');
cc.loader.release(deps);
// If there is no instance of this prefab in the scene, the prefab and its dependencies like textures, sprite frames, etc, will be freed up.
// If you have some other nodes share a texture in this prefab, you can skip it in two ways:
// 1. Forbid auto release a texture before release
cc.loader.setAutoRelease(texture2d, false);
// 2. Remove it from the dependencies array
var deps = cc.loader.getDependsRecursively('prefabs/sample');
var index = deps.indexOf(texture2d._uuid);
if (index !== -1)
    deps.splice(index, 1);
cc.loader.release(deps);
releaseAsset

Release the asset by its object. Refer to release for detailed informations.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:837
Parameters
releaseRes

Release the asset loaded by loadRes. Refer to release for detailed informations.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:851
Parameters
  • url String
  • type Function Only asset of type will be released if this argument is supplied.
releaseResDir

Release the all assets loaded by loadResDir. Refer to release for detailed informations.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:869
Parameters
  • url String
  • type Function Only asset of type will be released if this argument is supplied.
releaseAll

Resource all assets. Refer to release for detailed informations.

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:888
setAutoRelease

Indicates whether to release the asset when loading a new scene.
By default, when loading a new scene, all assets in the previous scene will be released or preserved according to whether the previous scene checked the "Auto Release Assets" option. On the other hand, assets dynamically loaded by using cc.loader.loadRes or cc.loader.loadResDir will not be affected by that option, remain not released by default.
Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.

See: cc.loader.setAutoReleaseRecursively, cc.loader.isAutoRelease

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:909
Parameters
  • assetOrUrlOrUuid Asset | String asset object or the raw asset's url or uuid
  • autoRelease Boolean indicates whether should release automatically
Examples
// auto release the texture event if "Auto Release Assets" disabled in current scene
cc.loader.setAutoRelease(texture2d, true);
// don't release the texture even if "Auto Release Assets" enabled in current scene
cc.loader.setAutoRelease(texture2d, false);
// first parameter can be url
cc.loader.setAutoRelease(audioUrl, false);
setAutoReleaseRecursively

Indicates whether to release the asset and its referenced other assets when loading a new scene.
By default, when loading a new scene, all assets in the previous scene will be released or preserved according to whether the previous scene checked the "Auto Release Assets" option. On the other hand, assets dynamically loaded by using cc.loader.loadRes or cc.loader.loadResDir will not be affected by that option, remain not released by default.
Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.

See: cc.loader.setAutoRelease, cc.loader.isAutoRelease

meta description
Defined in cocos2d/core/load-pipeline/CCLoader.js:949
Parameters
  • assetOrUrlOrUuid Asset | String asset object or the raw asset's url or uuid
  • autoRelease Boolean indicates whether should release automatically
Examples
// auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene
cc.loader.setAutoReleaseRecursively(spriteFrame, true);
// don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene
cc.loader.setAutoReleaseRecursively(spriteFrame, false);
// don't release the Prefab and all the referenced assets
cc.loader.setAutoReleaseRecursively(prefab, false);
isAutoRelease

Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.

See: cc.loader.setAutoRelease, cc.loader.setAutoReleaseRecursively

meta description
Returns Boolean
Defined in cocos2d/core/load-pipeline/CCLoader.js:997
Parameters
  • assetOrUrl Asset | String asset object or the raw asset's url
constructor

Constructor, pass an array of pipes to construct a new Pipeline, the pipes will be chained in the given order.
A pipe is an object which must contain an id in string and a handle function, the id must be unique in the pipeline.
It can also include async property to identify whether it's an asynchronous process.

meta description
Defined in cocos2d/core/load-pipeline/pipeline.js:112
Parameters
Examples
var pipeline = new Pipeline([
     {
         id: 'Downloader',
         handle: function (item, callback) {},
         async: true
     },
     {id: 'Parser', handle: function (item) {}, async: false}
 ]);
insertPipe

Insert a new pipe at the given index of the pipeline.
A pipe must contain an id in string and a handle function, the id must be unique in the pipeline.

meta description
Defined in cocos2d/core/load-pipeline/pipeline.js:156
Parameters
  • pipe Object The pipe to be inserted
  • index Number The index to insert
insertPipeAfter

!en Insert a pipe to the end of an existing pipe. The existing pipe must be a valid pipe in the pipeline. !zh 在当前 pipeline 的一个已知 pipe 后面插入一个新的 pipe。

meta description
Defined in cocos2d/core/load-pipeline/pipeline.js:199
Parameters
  • refPipe Object An existing pipe in the pipeline.
  • newPipe Object The pipe to be inserted.
appendPipe

Add a new pipe at the end of the pipeline.
A pipe must contain an id in string and a handle function, the id must be unique in the pipeline.

meta description
Defined in cocos2d/core/load-pipeline/pipeline.js:216
Parameters
  • pipe Object The pipe to be appended
flowIn

Let new items flow into the pipeline.
Each item can be a simple url string or an object, if it's an object, it must contain id property.
You can specify its type by type property, by default, the type is the extension name in url.
By adding a skips property including pipe ids, you can skip these pipe.
The object can contain any supplementary property as you want.

meta description
Defined in cocos2d/core/load-pipeline/pipeline.js:240
Parameters
Examples
pipeline.flowIn([
     'res/Background.png',
     {
         id: 'res/scene.json',
         type: 'scene',
         name: 'scene',
         skips: ['Downloader']
     }
 ]);
copyItemStates

Copy the item states from one source item to all destination items.
It's quite useful when a pipe generate new items from one source item,
then you should flowIn these generated items into pipeline,
but you probably want them to skip all pipes the source item already go through,
you can achieve it with this API.

For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again.

meta description
Defined in cocos2d/core/load-pipeline/pipeline.js:325
Parameters
  • srcItem Object The source item
  • dstItems Array | Object A single destination item or an array of destination items
getItem

Returns an item in pipeline.

meta description
Returns Object
Defined in cocos2d/core/load-pipeline/pipeline.js:354
Parameters
  • id Object The id of the item
removeItem

Removes an completed item in pipeline. It will only remove the cache in the pipeline or loader, its dependencies won't be released. cc.loader provided another method to completely cleanup the resource and its dependencies, please refer to cc.loader.release

meta description
Returns Boolean
Defined in cocos2d/core/load-pipeline/pipeline.js:374
Parameters
  • id Object The id of the item
clear

Clear the current pipeline, this function will clean up the items.

meta description
Defined in cocos2d/core/load-pipeline/pipeline.js:394

results matching ""

    No results matching ""