You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用offline.js实现离线AJAX请求排队及联网自动执行(附示例)

Offline AJAX Request Queuing Implementation

Let's modify your existing code to add the offline queuing functionality. The core idea is to store AJAX requests in a queue (using localStorage to persist it across page reloads) when offline, then automatically process the queue once the connection comes back online.

Step 1: Add Queue Management Variables & Helpers

First, we'll add variables to track the request queue, plus helper functions to save/load the queue from localStorage so it doesn't get lost if the page refreshes:

// Initialize request queue (load from localStorage if exists)
let ajaxQueue = JSON.parse(localStorage.getItem('ajaxQueue')) || [];

// Helper to save queue to localStorage
function saveQueue() {
  localStorage.setItem('ajaxQueue', JSON.stringify(ajaxQueue));
}

// Helper to process the queue
function processQueue() {
  if (Offline.state !== 'up') return; // Don't process if still offline

  // Clone the queue to avoid issues while modifying it
  const queueCopy = [...ajaxQueue];
  ajaxQueue = [];
  saveQueue(); // Clear the queue immediately to prevent reprocessing

  queueCopy.forEach(request => {
    $.ajax(request)
      .done(result => {
        console.log('Queued request succeeded:', JSON.stringify(result));
        // You can add custom success handling here (like updating UI)
        alert('Queued request completed: ' + JSON.stringify(result));
      })
      .fail(error => {
        console.error('Queued request failed:', error);
        // If a request fails, re-add it to the queue for next attempt
        ajaxQueue.push(request);
        saveQueue();
      });
  });
}

Step 2: Modify the getData Function

Update your getData function to check connectivity status. If we're offline, add the AJAX request details to the queue instead of executing it right away:

function getData() {
  Offline.check();

  const ajaxOptions = {
    url: "http://rest-service.guides.spring.io/greeting",
    success: function(result){
      console.log('Live request succeeded:', JSON.stringify(result));
      alert(JSON.stringify(result));
    },
    error: function(error){
      console.error('Live request failed:', error);
    }
  };

  if (Offline.state === 'up') {
    // Online: Execute request immediately
    $.ajax(ajaxOptions);
    // Also process any leftover queue items (in case we just came online)
    processQueue();
  } else {
    // Offline: Add request to queue
    ajaxQueue.push(ajaxOptions);
    saveQueue();
    alert('Request queued. Will execute when back online.');
    console.log('Request added to queue:', ajaxOptions);
  }
}

Step 3: Trigger Queue Processing When Going Online

Update your internetUp function to automatically kick off queue processing as soon as the connection is restored:

function internetUp(){
  console.log("Internet is up.");
  statusDiv.innerHTML = "Status is: up";
  // Process the queue immediately when back online
  processQueue();
}

Full Modified Code

Here's the complete code with all changes integrated, plus a small fix to cache-bust the offline check image:

<div id="status">Status is:</div>
<button onclick="getData()">Get Data</button>

<script>
// Set our options for the Offline detection library
Offline.options = {
  checkOnLoad: true,
  checks: {
    image: {
      url: function() { 
        return 'http://esri.github.io/offline-editor-js/tiny-image.png?' + Date.now(); // Add cache-bust param
      }
    }
  },
  active: 'image',
  requests : true
}

Offline.on('up', internetUp);
Offline.on('down',internetDown);

var statusDiv = document.getElementById("status");
statusDiv.innerHTML = "Status is: " + Offline.state;

// Initialize request queue (load from localStorage if exists)
let ajaxQueue = JSON.parse(localStorage.getItem('ajaxQueue')) || [];

// Helper to save queue to localStorage
function saveQueue() {
  localStorage.setItem('ajaxQueue', JSON.stringify(ajaxQueue));
}

// Helper to process the queue
function processQueue() {
  if (Offline.state !== 'up') return; // Don't process if still offline

  // Clone the queue to avoid issues while modifying it
  const queueCopy = [...ajaxQueue];
  ajaxQueue = [];
  saveQueue(); // Clear the queue immediately to prevent reprocessing

  queueCopy.forEach(request => {
    $.ajax(request)
      .done(result => {
        console.log('Queued request succeeded:', JSON.stringify(result));
        // Optional: Alert user when queued request completes
        alert('Queued request completed: ' + JSON.stringify(result));
      })
      .fail(error => {
        console.error('Queued request failed:', error);
        // Re-add failed request to queue for next attempt
        ajaxQueue.push(request);
        saveQueue();
      });
  });
}

function getData() {
  Offline.check();

  const ajaxOptions = {
    url: "http://rest-service.guides.spring.io/greeting",
    success: function(result){
      console.log('Live request succeeded:', JSON.stringify(result));
      alert(JSON.stringify(result));
    },
    error: function(error){
      console.error('Live request failed:', error);
    }
  };

  if (Offline.state === 'up') {
    // Online: Execute request immediately
    $.ajax(ajaxOptions);
    // Process any leftover queue items
    processQueue();
  } else {
    // Offline: Add request to queue
    ajaxQueue.push(ajaxOptions);
    saveQueue();
    alert('Request queued. Will execute when back online.');
    console.log('Request added to queue:', ajaxOptions);
  }
}

function internetUp(){
  console.log("Internet is up.");
  statusDiv.innerHTML = "Status is: up";
  // Process the queue as soon as we're back online
  processQueue();
}

function internetDown(){
  console.log("Internet is down.");
  statusDiv.innerHTML = "Status is: down";
}
</script>

Key Details to Note:

  • Persistence: localStorage ensures the queue stays intact even if the user closes or refreshes the browser.
  • Cache Busting: The Date.now() addition to the offline check image URL prevents cached responses from incorrectly showing "online" status.
  • Queue Safety: We clone the queue before processing to avoid bugs from modifying the queue while iterating over it.
  • Error Recovery: Failed requests get re-added to the queue, so they'll be retried next time the connection is restored.

内容的提问来源于stack exchange,提问作者Esrath Muqayyar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:28:47