2016-05-23 95 views
0

通常情况下,我会通过http2的文件服务解决这样的请求:更新缓存请求

if (req.url === '/main.html') { 
    let files = { 
    'main.css': { 
     type: 'text/css' 
    }, 
    'main.js': { 
     type: 'application/javascript' 
    } 
    }; 
    for (let name in files) { 
    let push = res.push('/' + name, { 
     response: { 
     'Content-Type': files[name].type, 
     'Cache-Control': 'public, max-age=31556926' 
     } 
    }); 
    push.on('error', er => console.log(er)); 
    push.end(fs.readFileSync('/home/src/' + name)); 
    } 
    res.writeHead(200, { 
    'Content-Type': 'text/html' 
    }); 
    res.end(` 
    <html> 
    <head> 
     <link rel="stylesheet" href="/main.css"> 
     <script src="/main.js"></script> 
    </head> 
    <body></body> 
    </html> 
`); 
} 

我有一个问题,当他们的新内容都可以更新这些2个文件main.cssmain.js。 它们会通过发送另一个/main.html请求来更新吗?如果不是,我如何更新它们?

回答

1

不,他们不会更新。当您尝试推送资产的新版本时,浏览器将重置流,因为它认为这些资产仍然是新鲜的。它将继续使用旧版本的资产。

至少现在,解决方案是使用高速缓存摘要机制缓存清除。

在这里阅读细节:

https://www.shimmercat.com/en/info/articles/caching/

又见this answer

+0

非常感谢您的回答。我还考虑通过'max-age'设置一个很短的生命期来移除旧的缓存。你有没有尝试过这种方法?它是否适用于所有浏览器? – Lewis

+0

嗨!是的,这种方法在Internet Explorer,Chrome和Firefox中运行良好。 Safari不支持HTTP/2 Push,所以不需要它。 – dsign