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

关于渐进式Web应用(PWA)中局部视图(Partial Views)的实现选项咨询

PWA局部视图的多种实现选项(不止Ajax)

Great question! When building PWAs, you have way more options than just Ajax for handling partial views—PWA’s core features like service workers and offline caching open up flexible, efficient approaches. Let’s walk through the most useful ones:

1. Service Worker 缓存 + Fetch API

Service workers let you intercept network requests for partial view fragments, serving cached versions first (for speed and offline access) or fetching fresh content from the network and updating the cache. This is a game-changer for PWAs since it makes partial views available even when the user is offline.

Example snippet of a service worker handling partial views:

self.addEventListener('fetch', (event) => {
  if (event.request.url.includes('/partial/')) {
    event.respondWith(
      caches.match(event.request)
        .then(cachedResponse => {
          // Return cached content if available, else fetch from network
          return cachedResponse || fetch(event.request)
            .then(networkResponse => {
              // Cache the fresh response for next time
              caches.open('partial-views').then(cache => {
                cache.put(event.request, networkResponse.clone());
              });
              return networkResponse;
            });
        })
    );
  }
});

2. 客户端模板渲染

Instead of fetching full HTML fragments via Ajax, you can cache template files (or inline templates using <template> tags) locally, then populate them with data using JavaScript. This reduces payload size since you’re only fetching data (JSON, usually) instead of full HTML.

For example, using a native <template>:

<template id="product-card-template">
  <div class="product-card">
    <h3 class="product-name"></h3>
    <p class="product-price"></p>
  </div>
</template>

Then in your JS:

// Get the template content
const template = document.getElementById('product-card-template').content;
// Fetch product data (could be from cache or network)
fetch('/api/products/123')
  .then(res => res.json())
  .then(product => {
    // Clone the template and populate data
    const card = document.importNode(template, true);
    card.querySelector('.product-name').textContent = product.name;
    card.querySelector('.product-price').textContent = `$${product.price}`;
    // Append to the page
    document.getElementById('products-container').appendChild(card);
  });

3. PWA Shell 架构

This approach involves caching your app’s static "shell" (navigation bar, footer, layout structure) upfront, then dynamically loading only the variable content sections (your partial views) as needed. Service workers ensure the shell loads instantly, and you can use Fetch or other methods to update the content area without reloading the entire page.

4. 流式响应 (ReadableStream)

Using the Fetch API with ReadableStream, your server can send partial view content in chunks. The browser renders each chunk as it arrives, which improves perceived performance—especially for long lists or content-heavy partial views. No need to wait for the entire response to load before showing something to the user.

5. Web Components

Custom elements (a core web component feature) let you encapsulate partial views into reusable, self-contained components. These components can handle their own data fetching, caching, and rendering. You can cache the component’s code via service workers, and instantiate them anywhere in your PWA. For example:

class UserProfile extends HTMLElement {
  connectedCallback() {
    // Fetch profile data (from cache or network)
    fetch(`/api/users/${this.getAttribute('user-id')}`)
      .then(res => res.json())
      .then(user => {
        this.innerHTML = `
          <div class="profile">
            <img src="${user.avatar}" alt="${user.name}">
            <h2>${user.name}</h2>
          </div>
        `;
      });
  }
}
customElements.define('user-profile', UserProfile);

Then use it in your HTML:

<user-profile user-id="456"></user-profile>

Key Takeaway

Ajax (Fetch/XHR) is a foundational tool, but PWAs amplify its capabilities with caching and offline support. The options above let you build faster, more resilient partial views that work seamlessly even when the network is spotty.

内容的提问来源于stack exchange,提问作者Ramesh Krishnamurthy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:54:44