Основная идея — проверять перед сохранением данных значение navigator.onLine и слушать события online (для сохранения на сервере), offline (для сохранения в localStorage) и load (для загрузки несохранённых данных на сервер при загрузке страницы после подключения к сети).
Пример:
Go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// save the string
functionsaveStatusLocally(txt){
window.localStorage.setItem("status",txt);
}
// read the string
functionreadStatus(){
returnwindow.localStorage.getItem("status");
}
functionwhatIsYourCurrentStatus(){
varstatus=window.prompt("What is your current status?");
if(!status)return;
if(navigator.onLine){
sendToServer(status);
}else{
saveStatusLocally(status);
}
}
functionsendLocalStatus(){
varstatus=readStatus();
if(status){
sendToServer(status);
window.localStorage.removeItem("status");
}
}
window.addEventListener("load",function(){
if(navigator.onLine){
sendLocalStatus();
}
},true);
window.addEventListener("online",function(){
sendLocalStatus();
},true);
window.addEventListener("offline",function(){
alert("You're now offline. If you update your status, it will be sent when you go back online");