Leverage browser caching for external files

2020-07-02 09:23发布

i'm trying to get my google page speed insights rating to be decent, but there are some external files that i would want to be cached aswell, anyone knows what would be the best way to deal with this?

https://s.swiftypecdn.com/cc.js (5 minutes)
https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js (60 minutes)
https://pagead2.googlesyndication.com/pagead/osd.js (60 minutes)
https://www.google-analytics.com/plugins/ua/linkid.js (60 minutes)
https://hey.hellobar.com/…d5837892514411fd16abbb3f71f0d400607f8f0b (2 hours)
https://www.google-analytics.com/analytics.js (2 hours)

4条回答
Melony?
2楼-- · 2020-07-02 09:52

set cache-control to external resources? You can't control the headers sent from a server that you don't control.

In other words, either host a copy yourself or there's nothing you can do about it.

Thanks

查看更多
地球回转人心会变
3楼-- · 2020-07-02 10:08

There is no solution for those files. If those files are CDN like bootstrap cdn you can copy those files locally into your host but if those request are generated on runtime than you can do nothing about it. :)

查看更多
等我变得足够好
4楼-- · 2020-07-02 10:17

Copy to your server and serve locally or from CDN, with different browser cache settings. Update GA scripts periodically with cronjob or something similar.

On Wordpress there are plugins that can do that for you, like this one: Above The Fold; they call this feature Javascript localization.

On the other hand, I use Google Pagespeed Module on server and it's directive MapProxyDomain in combination with Alternative async tracking snippet. That seems most elegant for me.

This should be enough for you to start solving your problem.

查看更多
冷血范
5楼-- · 2020-07-02 10:17

You can make your own cache

Place some files to the browser's localStorage (after the first time they arrive from the distant server) and next time you can serve them from the local copy. This way, you store things right where they're needed - the only thing to be careful with is updating them, you need a way to replace these files when it's time for a new version.

If you don't want to do this from scratch, here are some Javascript libraries:
https://www.sitepoint.com/9-javascript-libraries-working-with-local-storage/

Check out this lsCache for example, it looks super practical:

    lscache.set('greeting', 'Hello World!', 2);     // 2 minute expiration
    lscache.get('greeting');                        // returns "Hello World!"
    lscache.remove('greeting');                     // remove
    lscache.flush();                                // flush the entire cache
    lscache.flushExpired();                         // flush only expired items
查看更多
登录 后发表回答