js-新兴的API,最佳实践,离线应用于客户端存储

离线应用于客户端存储

1、离线检测:online以及offline事件,都是在window对象上触发

navigator.online为true的时候是表示设备能够上网

2、使用一个描述文件(manifest file)列出要下载以及缓存的资源

<html manifest ="/offline.manifest">

3、描述文件中的核心是applicationCache对象,该对象有一个status属性,属性的值是一个常量

0:无缓存 

1:闲置-应用缓存未得到更新

2:检查中-正在下载描述文件并且检查更新

3:下载中

4:更新完成,通过swapCache()来使用

5:废弃

相关的事件:

checking:在浏览器为应用缓存查找更新时触发

error:

noupdate:检查发现无变化

downloading:在开始下载应用缓存的时候开始触发

progress:在文件下载应用缓存的过程中不断触发

updateready:新的应用缓存下载完毕,并且可以通过swapCache()使用时触发

cached:在应用缓存完整可用的时候触发

EventUtil.addHandler(applicationCache,"updateready",function(){

      applicationCache.swapCache();

});

4、cooki的构成:

名称:不区分大小写,被URL编码

值:字符串值,被URL编码

域:

路径:

失效时间:

安全标志:在https安全下才发送cookie

每一段信息都作为Set-Cookie头的一部分,使用分号加空格分隔每一段

5、

var CookieUtil={

get:function(name){

      var cookieName=encodeURIComponent(name)+"=",

          cookieStart=document.cookie.indexOf(cookieName),

          cookieValue=null;

      if(cookieStart>-1){

           var cookieEnd=document.cookie.indexOf(";",cookieStart);

           if(cookieEnd==-1){

                 cookieEnd=document.cookie.length;

           }

        cookieValue=decodeURICompanent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd));

      }

      return cookieValue;

},

 set:function(name,value,expires,path,domain,secure){

     var cookieText=encodeURIComponent(name)+"="+encodeURIComponent(value);

     if(expires instanceof date){

           cookieText+="; expires="+expires.toGMTSring();

     }

     if(path){

           cookieText+="; path="+path;

     }

     if(domain){

           cookieText+="; domian="+domain;

     }

     if(secure){

           cookieText+="; secure"

     }

     documment.cookie=cookieText;

 },

 unset:function(name,path,domain,secure){

     this.set(name,"",new Date(0),path,domain,secure);

 }

};

//设置cookie

CookieUtil.set("name","zhang");

CookieUtil.set("book","aaaa");

//读取cookie的值

alert(CookieUtil.get("name"));

alert(CookieUtil.get("book"));

//删除cookie

CookieUtil.unset("name");

CookieUtil.unset("book");

//设置cookie

CookieUtil.set("name","zhang","/books/proj/","www.wrox.com",new Date("January 1,2010"))

//删除刚设置的cookie

CookieUtil.unset("name","/books/proj/","www.wrox.com");

//设置安全的cookie

CookieUtil.set("name","zhang",null,null,null,true);

6、web存储机制

  1.  

sessionStorage对象:

//使用方法存储

sessionStorage.setItem("name","zhang");

//使用属性存储数据

sessionStorage.book="ppppp";

//使用方法获取

var name=sessionStorage.getItem("name");

//使用属性获取

var book=sessionStorage.book;

迭代sessionStorage中的值:

for(var i=0,len=sessionStorage.length;i<len;i++){

      var key=sessionStorage.key(i);

      var value=sessionStorage.getItem(key);

      alert(key+"="+value);

}

Key方法取得指定位置上的名字,getItem()找出对应名字的值

删除数据:

delete sessionStorage.name;

sessionStorage.removeItem("book");

  1.  

storage事件:

domain:发生变化的存储空间的域名

key:设置或删除的键名

newValue:如果是设置值,则是新值,如果是删除键,则是null

oldValue:键被更改之前的值

EventUtil.addHandler(document,"storage",function(event){

      alert("Storage changed for"+event.domian);

});

7、IE用户数据

<div style="behavior:url(#default#userData)" id="dataStore"></div>

dataStore.setAttribute("name","zhang");

dataStore.setAttribute("book","zzzz");

dataStore.save("BookInfo");

dataStore.load("BookInfo");

alert(dataStore.getAttribute("name"));

alert(dataStore.getAttribute("book"));

dataStore.removeAttribute("name");

dataStore.removeAttribute("book");

dataStore.save("BookInfo");

8、IndexedDB:保存结构化数据的一种数据库,异步进行的,触发onerror或onsuccess事件,操作以请求方式进行,这些操作会在后期执行

var indexedDB=window.indexedDB || window.msIndexedDB || window.mozIndexedDB || window.webkitIndexedDB;

  1. 打开indexDB.open()

if(database.version!="1.0"){

var request,database;

request=database.setVersion("1.0");

request=indexedDB.open("admmin");

request.onerror=function(event){

      alert("something bad happened while trying to open:"+

           event.target.errorCode);

};

request.onsuccess=function(event){

      database=event.target.result;

};

}else{

      alert("database initalization.Database name:"+database.name+", Version:" + database.version);

}

  1. 对象存储空间

var store=db.createObjectStorage("users",{keyPath:"username"})

  1. add()以及put()方法向其中添加数据,接收一个参数,及要保存的对象

区别是在空间中已经包含了键值相同的对象时候会体现出来,add会返回错误,put会重写原有对象,add是插入新值,put是更新

var i=0,

    request,

    requests=[];

while(i<len){

      request=store.add(users[i++]);

      request.onerror=function(){

      };

      request.onsuccess=function(){

      };

      requests.push(request);

}

  1. 事务:

var transaction=db.transaction("uesrs");---只读

READ_WRITE--读写

VERSION_CHANGE--改变

READ_ONLY--只读

var transaction=db.transaction("uesrs",IDBTransaction. READ_WRITE-);

var transaction=db.transaction("uesrs").objectStore("users").get("007");

  1. 在oncomplete事件中的事件对象是访问不到get()请求返回任何的数据,只有在onsuccess事件处理程序中才能访问到数据
  2. 使用事务可以直接通过已知的键检索单个对象,在需要检索多个对象的情况下,则需要在事务内创建游标openCursor()

var store =db.transaction("uesrs").objectStore("users"),

    request=store.openCursor();

request.onsuccess=function(event){

};

request.onerror=function(event){

};

在onsucce事件处理程序执行中,通过event.target.result取得下一个对象

在结果集中有下一项的时候,属性保存IDBCursor的实例,没有下一项的时候,值为null

direction:数值,表示游标移动的方向IDBCCursor.NEXT(0),表示下一项,

IDBCursor.NEXT_NO_DUPLICATE表示下一项不重复的项,DBCursor.PREV(2)表示上一项,DBCursor.PREV_NO_DUPLICATE表示前一个不重复的项

key:对象的键

value:实际的对象

primaryKey:游标使用的键

request.onsuccess=function(event){

      var cursor=event.target.result;

      if(cursor){

           console.log("key:"+cursor.key+",value:"+JSON.stringify|cursor.value);

      }

};

delete(),请求删除当前项

continue(key):移动到结果集中的下一项,参数key是可选的,不指定这个参数,游标移动到下一项,指定这个参数,游标会移动到指定键的位置

advance(count):向前移动count指定的项数

最佳实践

1、

var found=false;  //boolean

var count=-1; //数字

var name=""; //string

var person=null;//object

var bFound; //boolean

var iCount;//数字

var sName;//string

var oPerson;//object

2、

function sortArray(values){

      if(value != null){  //不推荐

           values.sort(comparator);

      }

}

function sortArray(values){

    if(value instanceof Array){ //推荐

           values.sort(comparator);

      }

}

3、避免全局查找

var doc=document;

var image=doc.getAttribute("img")

4、

var list=document.getElementById("myList"),

    html="",

    i;

for(i=0;i<10;i++){

      html+="<li>Item"+i+"</li>";

}

list.innerHTML=html;

var list=document.getElementById("myList"),

    i;

for(i=0;i<10;i++){

  list.innerHTML+="<li>Item"+i+"</li>";  //避免

}

新兴的API

1、页面是否对用户可见:

document.hidden:表示页面是否掩藏的布尔值

document.visibilityState:在后台标签中或浏览器最小化;在前台标签页中;

实际的页面已经掩藏,用户可以看到预览,eg:在鼠标放在那位置上的时候,可以看到当前页面的预览;

页面在屏幕外执行预渲染处理

Visibilitychange事件:文档从可变变为不可见或者不可见变为可见的时候

if(document.hidden || document.msHidden || document.webkitHidden){

}else{

      //页面未掩藏

}

EventUtil.addHandler(document,"msvisibilitychange",handleVisibilityChange);

2、地理定位:navigator.geolocation对象

getCurrentPosition();接收3个参数,成功回调函数,可选的失败回调函数,可选的选项对象

成功回调函数接收一个Position对象参数,该对象有两个属性,coords以及timestamp

coords对象包含以下位置相关信息:

latitude:十进制表示的纬度

longtitude:十进制表示的经度

accuracy:经,纬度坐标的经度,以米为单位

3、File API:file对象

name:

size:文件的字节大小

type:字符串,文件的mime类型

lastModifiedDate:文件上一次修改的时间,字符串

var filesList=document.getElementById("files-list");

EventUtil.addHandler(filesList,"change",function(event){

      var files=EventUtil.getTarget(event).files,

          i=0,

          len=files.length;

      while(i<len){

           console.log(files[i].name+"("+files[i]+","+files[i].size+"bytes")"};

                 i++;

      }

});

4、

readAsText(file,encoding):以纯文本的形式读取文件,将读取的文本存到result属性中

readAsDataURL(file):读取文件并以数据url的形式保存在result属性中

readAsArrayBuffer(file):读取文件,并将包含文件内容的ArrayBuffer存在result属性中

事件:progress(是否又读取了新数据),error,load

var fileList=document.getElementById("files-list");

EventUtil.addHandler(fileList,"change",function(event){

      var info="",

          output=document.getElementById("output"),

          progress=document.getElementById("progress"),

          files=EventUtil.getTarget(event).files,

          type="default",

          reader=new FileReader();

      if(/image/.test[files[0].type]){

           reader.readAsDataURL(files[0]);

           type="image";

      }else{

           reader.readAsText(files[0]);

           type="text";

      }

      reader.onerror=function(){

            output.innerHTML="Could     ";

      };

      reader.onprogress=function(event){

           if(event.lengthComputable){

                 progress.innerHTML=event.loadded+"/"+event.total;

           }

      };

      reader.onlaod=function(){

           var html="";

           switch(type){

                 case "image":

                 html="<image src=""+reader.result+"">";

                 break;

                 case "text":

                 html=reader.result;

                 break;

           }

           output.innerHTML=html;

      };

});

中断读取过程,可以调用abort()方法,触发abort事件,

5、读取部分内容

Slice()方法,接收两个参数,起始节点以及要读取的字节数,返回一个Blob的实例

6、读取拖放的文件

在event.dataTransfer.file中读取到被放置的文件

触发的是dragenter以及dragover以及drop事件

7、使用XHR上传文件

var droptarget=document.getElementById("droptarget");

function handleEvent(event){

      var info="",

           output=document.getElementById("output"),

           data,

           xhr,

           files,

           i,

           len;

      EventUtil.preventDefault(event);

      if(event.type=="drop"){

           data=new FormData();

           files=event.dataTransfer.files;

           i=0;

           len=files.length;

           while(i<len){

                 data.append("file"+i,files[i]);

                 i++;

           }

           xhr=new XMLHttpRequest();

           xhr.open("post","FileAPIExample06Upload.php",true);

           xhr.onreadystate==4){

              alert(xhr.responseText);

         };

            xhhr.send(data);

      }

}

EventUtil.addHandler(droptarget,"dragenter",handleEvent);

EventUtil.addHandler(droptarget,"dragover",handleEvent);

EventUtil.addHandler(droptarget,"drop",handleEvent);

原文地址:https://www.cnblogs.com/zhanghuiyun/p/5162527.html