IndexedDB使用
使用IndexedDB来缓存游戏图片
针对H5游戏开发资源加载慢的问题,保存图片资源到本地缓存,加快资源加载速度。好的,闲话少说,切入正题,下面讲具体的操作步骤。
IndexedDB
module game {
/**资源数据库处理 */
export class ResDBMgr {
private static _indexedDb;
public static db;
public static hasInit = false;
public static hasDB = false;
public static dbVersion = 108;
public static dbName = "resource";
public constructor() {
}
/**
* 获取图片资源
* url : 链接Url
* callFunc 成功回调
* errFunc 失败回调
* */
public static getImage(url , callFunc , errFunc , callObj)
{
try{
let tran = this.db.transaction(this.dbName, "readwrite");
let store = tran.objectStore(this.dbName);
if(url)
{
let request = store.get(url);
if(!request)
{
if(errFunc)
{
errFunc.call(callObj , url);
}
return;
}
request.onsuccess = function(){
let data = request.result;
if(data && data.res)
{
if(callFunc)
{
callFunc.call(callObj , data['res'] , url);
}
}else{
if(errFunc)
{
errFunc.call(callObj , url);
}
}
}
request.onerror = function(){
if(errFunc)
{
errFunc.call(callObj , url);
}
}
}
}catch(e){
//报错处理
if(errFunc)
{
errFunc.call(callObj , url);
}
}
}
/**保存数据操作 */
public static saveImage(url , res): void {
if(this.db)
{
var transaction = this.db.transaction(this.dbName, "readwrite");
var put = transaction.objectStore(this.dbName).put({url:url , res:res});
put.onerror = function(evt){
ResDBMgr.deleteImg(url);
}
}
}
/**删除资源处理 */
public static deleteImg(url:string):void
{
let request = this.db.transaction(this.dbName , "readwrite").objectStore(this.dbName).delete(url);
}
public static clear():void
{
var request = this.db.transaction(this.dbName,"readwrite").objectStore(this.dbName).clear();
}
public static init(): void {
// IndexedDB
if(this.hasInit)
{
return;
}
this.hasInit = true;
var indexedDB = window.indexedDB || window['webkitIndexedDB'] || window['mozIndexedDB'] || window['OIndexedDB'] || window['msIndexedDB'],
IDBTransaction = window['IDBTransaction'] || window['webkitIDBTransaction'] || window['OIDBTransaction'] || window['msIDBTransaction'],
dbVersion = this.dbVersion;
this._indexedDb = indexedDB;
let that = this;
//创建数据库处理
var request = indexedDB.open("jdqk_resource", dbVersion);
var db;
request.onerror = function (event) {
//数据库错误处理
};
request.onsuccess = function (evt) {
db = evt.target.result;
that.db = db;
}
request.onupgradeneeded = function (evt) {
db = evt.target.result;
if(!db.objectStoreNames.contains(that.dbName))
{
db.createObjectStore(that.dbName , {keyPath:"url"});
}
that.db = db;
};
}
}
}