我的页面是否从浏览器缓存中加载? [英] Is My Page Being Loaded from the Browser Cache?

查看:449
本文介绍了我的页面是否从浏览器缓存中加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面上有一个新项目徽章,我想立即更新页面从缓存中加载(即,当点击返回或转发返回此页面时)。实现这一目标的最佳方法是什么?

I have a "new items" badge on a page that I want to update immediately the page is loaded from the cache (i.e. when hitting "Back" or "Forward" to return to this page). What is the best way to accomplish this?

设置非常简单。应用程序的布局每8秒查找一个新项目,并相应地更新徽章+项目列表。

The setup is pretty simple. The layout for the app looks for new items every 8 seconds, and updates the badge + list of items accordingly.

$(function() {
    setInterval( App.pollForNewItems, 8000 );
});

当有人离开此页面查看项目的详细信息时,可能会发生很多事情。在任何用户查看它们之前,事情是新的,并且应用程序可能会有多个用户同时使用它(用于呼叫中心或支持服务单的工作流程类型)。

When someone navigates away from this page to look at the details of an item, a lot can happen. Things are "new" until any user has viewed them, and the app will likely have several user using it simultaneously (the kind of workflow used for a call center or support tickets).

为了确保徽章始终是最新的,我有:

To make sure that the badges are always up to date, I have:

$(window).bind('focus load', function ( event ) {
    App.pollForNewItems();
});

..虽然这有效,但在加载上轮询新项目仅在页面上有用从缓存加载。是否有可靠的跨浏览器方式来判断是否正在从缓存中加载页面?

..And though this works, polling for new items on 'load' is only useful when the page is loaded from the cache. Is there a reliable cross-browser way to tell if a page is being loaded from the cache?

推荐答案

部分hacky解决方案是使用服务器上设置的当前时间的var,并使用页面顶部的当前客户端时间设置var。如果它们的差异超过某个阈值(1分钟?),那么你可以假设它是一个缓存的页面加载。

A partial hacky solution is to have a var with the current time set on the server, and set a var with the current client time at the top of the page. If they differ by more than a certain threshold (1 minute?) then you could assume it's a cached page load.

示例JS(使用服务器的ASP.Net语法)方):

Example JS (using ASP.Net syntax for the server side):

var serverTime = new Date('<%= DateTime.Now.ToUniversalTime().ToString() %>');
var pageStartTime = Date.UTC(new Date());
var isCached = serverTime < pageStartTime &&
               pageStartTime.getTime() - serverTime.getTime() > 60000;

或者,在客户端使用cookie(假设已启用cookie),您可以检查cookie使用当前版本页面的唯一键。如果不存在,则为其编写cookie,并且在任何其他页面访问中,cookie的存在表明它正在从缓存中加载。

Alternatively, using cookies on the client side (assuming cookies are enabled), you can check for a cookie with a unique key for the current version of the page. If none exists, you write a cookie for it, and on any other page access, the existence of the cookie shows you that it's being loaded from the cache.

例如。 (假设有一些cookie辅助函数可用)

E.g. (assumes some cookie helper functions are available)

var uniqueKey = '<%= SomeUniqueValueGenerator() %>';
var currentCookie = getCookie(uniqueKey);
var isCached = currentCookie !== null;
setCookie(uniqueKey); //cookies should be set to expire 
                      //in some reasonable timeframe

这篇关于我的页面是否从浏览器缓存中加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆