Leverage browser caching for external files

爱⌒轻易说出口 提交于 2020-06-10 07:43:29

问题


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)

回答1:


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.




回答2:


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:


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:


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


来源:https://stackoverflow.com/questions/36998214/leverage-browser-caching-for-external-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!