存儲
- localStorage
存儲:
window.localStorage.setItem('key', 'value');
取值:
window.localStorage.getItem('key');
刪除:
window.localStorage.removeItem('key');
清除:
window.localStorage.clear();
長度:
window.localStorage.length
- sessionStorage
存儲:
window.sessionStorage.setItem('key', 'value');
取值:
window.sessionStorage.getItem('key');
刪除:
window.sessionStorage.removeItem('key');
清除:
window.sessionStorage.clear();
長度:
window.sessionStorage.length
sessionStorate让簿、localStorage蹦骑、cookies三者區(qū)別:
1. sessionStorate和localStorage存儲空間更大, 5M或者更大素挽;cookie存儲一般不能超過4kb。
2. sessionStorate和localStorage不會自動把數(shù)據(jù)發(fā)給服務器,僅為本地存儲秸谢;cookie在每次http請求都會傳送到服務端。
3. sessionStorage不在不同的瀏覽器窗口中共享,即使是同一個頁面商叹;localStorage在所有同源窗口中都是共享的;cookie也是在所有同源窗口中都是共享的只泼。
4. sessionStorate和localStorage支持事件通知機制沈自,可以將數(shù)據(jù)更新的通知發(fā)送給監(jiān)聽者。
ApplicationCache
優(yōu)點:
1. 離線瀏覽 - 用戶可在離線時瀏覽您的完整網(wǎng)站
2. 速度 - 緩存資源為本地資源辜妓,因此加載速度較快枯途。
3. 服務器負載更少 - 瀏覽器只會從發(fā)生了更改的服務器下載資源
<!DOCTYPE html>
<html manifest="cache.manifest" type="text/cache-manifest">
<head>
<meta charset="UTF-8">
<title>manifest</title>
</head>
<body>

</body>
</html>
瀏覽器會打印如下信息:
Creating Application Cache with manifest http://localhost:5555/index/cache.manifest
cache:1 Application Cache Checking event
cache:1 Application Cache Downloading event
cache:1 Application Cache Progress event (0 of 1) http://localhost:5555/images/default_pic.jpg
cache:1 Application Cache Progress event (1 of 1)
cache:1 Application Cache Cached event
manifest屬性可指向絕對網(wǎng)址或相對路徑,但絕對網(wǎng)址必須與相應的網(wǎng)絡應用同源籍滴。清單文件可使用任何文件擴展名酪夷,但必須以正確的MIME類型提供。
cache.manifest文件配置如下:
CACHE MANIFEST
# 2010-06-18:v3
# Explicitly cached entries
/index.html
/images/default_pic.jpg
# offline.html will be displayed if the user is offline
FALLBACK:
/ /offline.html
# All other resources (e.g. sites) require the user to be online.
NETWORK:
*
# Additional resources to cache
CACHE:
/images/logo1.png
/images/logo2.png
/images/logo3.png
CACHE:
這是條目的默認部分孽惰。系統(tǒng)會在首次下載此標頭下列出的文件(或緊跟在 CACHE MANIFEST 后的文件)后顯式緩存這些文件晚岭。
NETWORK:
此部分下列出的文件是需要連接到服務器的白名單資源。無論用戶是否處于離線狀態(tài)勋功,對這些資源的所有請求都會繞過緩存坦报】馑担可使用通配符。
FALLBACK:
此部分是可選的片择,用于指定無法訪問資源時的后備網(wǎng)頁潜的。其中第一個 URI 代表資源,第二個代表后備網(wǎng)頁字管。兩個 URI 必須相關(guān)啰挪,并且必須與清單文件同源〕笆澹可使用通配符亡呵。
更新緩存
var appCache = window.applicationCache;
appCache.update(); // Attempt to update the user's cache.
...
if (appCache.status == window.applicationCache.UPDATEREADY) {
appCache.swapCache(); // The fetch was successful, swap in the new cache.
}
update()獲取新的應用緩存
swapCache()將原緩存換成新緩存
此流程只是讓瀏覽器檢查是否有新的清單、下載指定的更新內(nèi)容以及重新填充應用緩存硫戈。
上述過程需要對網(wǎng)頁進行兩次重新加載才能向用戶提供新的內(nèi)容锰什,其中第一次是獲得新的應用緩存,第二次是刷新網(wǎng)頁內(nèi)容丁逝。
為了避免重新加載兩次的麻煩汁胆,可以設置監(jiān)聽器
// Check if a new cache is available on page load.
window.addEventListener('load', function(e) {
window.applicationCache.addEventListener('updateready', function(e) {
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
// Browser downloaded a new app cache.
// Swap it in and reload the page to get the new hotness.
window.applicationCache.swapCache();
if (confirm('A new version of this site is available. Load it?')) {
window.location.reload();
}
} else {
// Manifest didn't changed. Nothing new to server.
}
}, false);
}, false);
Drag and Drop
<div id="drag1" class="drag"></div>

var drag1 = document.getElementById('drag1');
var drag2 = document.getElementById('drag2');
drag1.addEventListener('dragover', function (event) {
event.preventDefault();
}, false);
drag1.addEventListener('drop', function (event) {
event.preventDefault();
var id = event.dataTransfer.getData('id');
drag1.appendChild(document.getElementById(id));
}, false)
drag2.addEventListener('dragstart', function(event) {
event.dataTransfer.setData('id', event.target.id);
}, false);
屬性 | 描述 |
---|---|
ondrag | 元素被拖動時運行的腳本 |
ondragstart | 在拖動操作開端運行的腳本 |
ondragover | 當元素在有效拖放目標上正在被拖動時運行的腳本 |
ondragenter | 當元素元素已被拖動到有效拖放區(qū)域時運行的腳本 |
ondragleave | 當元素離開有效拖放目標時運行的腳本 |
ondragend | 在拖動操作末端運行的腳本 |
ondrop | 當被拖元素正在被拖放時運行的腳本 |
event.dataTrasfer.setData(),設置一個key-value果港。
dragover事件沦泌,默認地,數(shù)據(jù)/元素無法被放置到其他元素中辛掠。為了實現(xiàn)拖放谢谦,我們必須阻止元素的這種默認的處理方式。
drop事件的默認行為是以鏈接形式打開萝衩。
Web Workers
JavaScript語言采用的是單線程模型回挽,Web Worker的目的,就是為JavaScript創(chuàng)造多線程環(huán)境猩谊,允許主線程將一些任務分配給子線程千劈。在主線程運行的同時,子線程在后臺運行牌捷,兩者互不干擾墙牌。等到子線程完成計算任務,再把結(jié)果返回給主線程暗甥。
主線程 main.js
var worker = new Worker('worker.js');
worker.postMessage('I am main.js');
worker.addEventListener('message', function (event) {
console.log('main receive:' + event.data);
}, false);
子線程 worker.js
self.addEventListener('message', function (event) {
console.log('worker receive:' + event.data);
self.postMessage('I am worker.js');
}, false);
關(guān)閉主線程
worker.terminate();
關(guān)閉子線程
self.close();
Web Sockets
客戶端
var connection = new WebSocket('ws://localhost:5555', 'echo-protocol');
connection.onopen = function (event) {
console.log('open')
connection.send('This is a client')
}
connection.onmessage = function (event) {
console.log('message:' + event.data)
}
connection.onclose = function (event) {
console.log('close')
}
服務端(node.js)
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var WebSocketServer = require('websocket').server;
var wsServer = new WebSocketServer({
httpServer: server
});
var connection;
wsServer.on('request', function(req){
connection = req.accept('echo-protocol', req.origin);
connection.on('message', function(message) {
var msgString = message.utf8Data;
console.log(msgString)
connection.sendUTF(msgString);
});
});
注:socket.io是目前最流行的WebSocket實現(xiàn)
History
- history.pushState()
pushState方法不會觸發(fā)頁面刷新喜滨,只是導致history對象發(fā)生變化,地址欄會有反應撤防。
history.pushState()接收3個參數(shù)
state:一個與指定網(wǎng)址相關(guān)的狀態(tài)對象虽风,popstate事件觸發(fā)時,該對象會傳入回調(diào)函數(shù)。如果不需要這個對象辜膝,此處可以填null无牵。
title:新頁面的標題,但是所有瀏覽器目前都忽略這個值厂抖,因此這里可以填null茎毁。
url:新的網(wǎng)址,必須與當前頁面處在同一個域验游。瀏覽器的地址欄將顯示這個網(wǎng)址充岛。
var stateObj = {'page': '1'};
history.pushState(stateObj, 'title', '?debug=1');
- history.replaceState()
replaceState方法參數(shù)和pushState方法參數(shù)相同保檐,但是會修改瀏覽歷史中當前紀錄耕蝉。
history.replaceState(null, null, '?page=2');
- history.state
history.pushState({page: 1}, null, '?page=1');
history.state
{page: 1}
- popstate事件
每當同一個文檔的瀏覽歷史(即history對象)出現(xiàn)變化時,就會觸發(fā)popstate事件夜只。僅僅調(diào)用pushState方法或replaceState方法 垒在,并不會觸發(fā)該事件,只有用戶點擊瀏覽器倒退按鈕和前進按鈕扔亥,或者使用JavaScript調(diào)用back场躯、forward、go方法時才會觸發(fā)旅挤。另外踢关,該事件只針對同一個文檔,如果瀏覽歷史的切換粘茄,導致加載不同的文檔签舞,該事件也不會觸發(fā)。
window.onpopstate = function (event) {
console.log('location: ' + document.location);
console.log('state: ' + JSON.stringify(event.state));
};
// 或者
window.addEventListener('popstate', function(event) {
console.log('location: ' + document.location);
console.log('state: ' + JSON.stringify(event.state));
});