loader Class
Extends Pipeline
Module: cc
Loader for resource loading process. It's a singleton object.
Index
Properties
assetLoaderObjectThe asset loader in cc.loader's pipeline, it's by default the first pipe.downloaderObjectThe downloader in cc.loader's pipeline, it's by default the second pipe.loaderObjectThe downloader in cc.loader's pipeline, it's by default the third pipe.
Methods
getXMLHttpRequestGets a new XMLHttpRequest instance.addDownloadHandlersAdd custom supported types handler or modify existing type handler for download process.addLoadHandlersAdd custom supported types handler or modify existing type handler for load process.loadLoad resources with a progression callback and a complete callback.loadResLoad resources from the "resources" folder inside the "assets" folder of your project.
...loadResArrayThis method is like loadRes except that it accepts array of url.loadResDirLoad all assets in a folder inside the "assets/resources" folder of your project.
...getResGet resource data by id.getDependsRecursivelyGet all resource dependencies of the requested asset in an array, including itself.releaseRelease the content of an asset or an array of assets by uuid.releaseAssetRelease the asset by its object.releaseResRelease the asset loaded by loadRes.releaseResDirRelease the all assets loaded by loadResDir.releaseAllResource all assets.setAutoReleaseaccording to whether the previous scene checked the "Auto Release Assets" option.setAutoReleaseRecursivelyaccording to whether the previous scene checked the "Auto Release Assets" option.isAutoReleaseReturns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.
...constructorConstructor, pass an array of pipes to construct a new Pipeline,...insertPipeInsert a new pipe at the given index of the pipeline.insertPipeAfterInsert a pipe to the end of an existing pipe.appendPipeAdd a new pipe at the end of the pipeline.flowInLet new items flow into the pipeline.flowInDepsLet new items flow into the pipeline and give a callback when the list of items are all completed.copyItemStatesCopy the item states from one source item to all destination items.isFlowingReturns whether the pipeline is flowing (contains item) currently.getItemsReturns all items in pipeline.getItemReturns an item in pipeline.removeItemRemoves an completed item in pipeline.clearClear 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:100 |
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:108 |
loader
The downloader 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:117 |
Methods
getXMLHttpRequest
Gets a new XMLHttpRequest instance.
| meta | description |
|---|---|
| Returns | XMLHttpRequest |
| Defined in | cocos2d/core/load-pipeline/CCLoader.js:147 |
addDownloadHandlers
Add custom supported types handler or modify existing type handler for download process.
| meta | description |
|---|---|
| Defined in | cocos2d/core/load-pipeline/CCLoader.js:154 |
Parameters
extMapObject 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:168 |
Parameters
extMapObject 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:182 |
Parameters
resourcesString | String[] | Object Url list in an arrayprogressCallbackFunction Callback invoked when progression changecompleteCallbackFunction 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:405 |
Parameters
urlString Url of the target resource.The url is relative to the "resources" folder, extensions must be omitted.typeFunction Only asset of type will be loaded if this argument is supplied.progressCallbackFunction Callback invoked when progression change.completeCallbackFunction Callback invoked when the resource loaded.
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:528 |
Parameters
urlsString[] Array of URLs of the target resource.The url is relative to the "resources" folder, extensions must be omitted.typeFunction Only asset of type will be loaded if this argument is supplied.progressCallbackFunction Callback invoked when progression change.completeCallbackFunction A callback which is called when all assets have been loaded, or an error occurs.
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:586 |
Parameters
urlString Url of the target folder.The url is relative to the "resources" folder, extensions must be omitted.typeFunction Only asset of type will be loaded if this argument is supplied.progressCallbackFunction Callback invoked when progression change.completeCallbackFunction A callback which is called when all assets have been loaded, or an error occurs.errorError If one of the asset failed, the complete callback is immediately calledwith the error. If all assets are loaded successfully, error will be null.assetsAsset[] | Array An array of all loaded assets.If nothing to load, assets will be an empty array.urlsString[] 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:665 |
Parameters
getDependsRecursively
Get all resource dependencies of the requested 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:702 |
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:743 |
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:805 |
Parameters
assetAsset
releaseRes
Release the asset loaded by loadRes. Refer to release for detailed informations.
| meta | description |
|---|---|
| Defined in | cocos2d/core/load-pipeline/CCLoader.js:819 |
Parameters
releaseResDir
Release the all assets loaded by loadResDir. Refer to release for detailed informations.
| meta | description |
|---|---|
| Defined in | cocos2d/core/load-pipeline/CCLoader.js:837 |
Parameters
releaseAll
Resource all assets. Refer to release for detailed informations.
| meta | description |
|---|---|
| Defined in | cocos2d/core/load-pipeline/CCLoader.js:853 |
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:874 |
Parameters
assetOrUrlOrUuidAsset | String asset object or the raw asset's url or uuidautoReleaseBoolean 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:914 |
Parameters
assetOrUrlOrUuidAsset | String asset object or the raw asset's url or uuidautoReleaseBoolean 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:962 |
Parameters
constructor
Constructor, pass an array of pipes to construct a new Pipeline,
the pipes will be chained in the given order.</br>
A pipe is an object which must contain an id in string and a handle function,
the id must be unique in the pipeline.</br>
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
pipesArray
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. </br>
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
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
appendPipe
Add a new pipe at the end of the pipeline. </br>
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
pipeObject The pipe to be appended
flowIn
Let new items flow into the pipeline. </br>
Each item can be a simple url string or an object,
if it's an object, it must contain id property. </br>
You can specify its type by type property, by default, the type is the extension name in url. </br>
By adding a skips property including pipe ids, you can skip these pipe. </br>
The object can contain any supplementary property as you want. </br>
| meta | description |
|---|---|
| Defined in | cocos2d/core/load-pipeline/pipeline.js:240 |
Parameters
itemsArray
Examples
pipeline.flowIn([
'res/Background.png',
{
id: 'res/scene.json',
type: 'scene',
name: 'scene',
skips: ['Downloader']
}
]);
flowInDeps
Let new items flow into the pipeline and give a callback when the list of items are all completed. </br> This is for loading dependencies for an existing item in flow, usually used in a pipe logic. </br> For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded </br> after all its dependencies are loaded, then you will need to use function to flow in all dependencies </br> found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback).
| meta | description |
|---|---|
| Returns | Array |
| Defined in | cocos2d/core/load-pipeline/pipeline.js:288 |
| Deprecated | since v1.3 |
Parameters
copyItemStates
Copy the item states from one source item to all destination items. </br> It's quite useful when a pipe generate new items from one source item,</br> then you should flowIn these generated items into pipeline, </br> but you probably want them to skip all pipes the source item already go through,</br> you can achieve it with this API. </br> </br> 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
srcItemObject The source itemdstItemsArray | Object A single destination item or an array of destination items
isFlowing
Returns whether the pipeline is flowing (contains item) currently.
| meta | description |
|---|---|
| Returns | Boolean |
| Defined in | cocos2d/core/load-pipeline/pipeline.js:354 |
| Deprecated | since v1.3 |
getItems
Returns all items in pipeline. Returns null, please use API of Loader or LoadingItems.
| meta | description |
|---|---|
| Returns | LoadingItems |
| Defined in | cocos2d/core/load-pipeline/pipeline.js:365 |
| Deprecated | since v1.3 |
getItem
Returns an item in pipeline.
| meta | description |
|---|---|
| Returns | Object |
| Defined in | cocos2d/core/load-pipeline/pipeline.js:376 |
Parameters
idObject 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:396 |
Parameters
idObject 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:416 |