简体   繁体   中英

How can I measure the CDN hit rate of a CSS file?

I'm serving a webfont from a CDN . I want to know the percentage of visitors that already have the file cached locally.

Is there a way to measure this with JavaScript?

You can use the link.onLoad event and the Navigation Timing API to calculate how long it takes each CSS file to load. Both API's are supported on modern browsers.

If you need insight into the hit rate of older browsers[0] you could use an <img> tag with the src set to your css. Then measure the time in the onerror event, which is fired when the browser loads the file and figures out it's not actually an image. This technique is described here .

The most thorough solution would be to A/B test both options with JavaScript to see which one loads faster on average[1] for your specific visitors.


[0] I would guess older browsers would have a lower CDN hit rate simply because their default cache sizes are much smaller.

[1] Standard statistical disclaimers apply, eg you may want to optimize for best 95% percentile instead of the best average latency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM