Hacker News new | comments | ask | show | jobs | submit login

You could do that, but there's a performance benefit to doing it with srcset/sizes in the html.

The cascading part of CSS means the a later rule could override an earlier one, so to determine which image variant to download when looking at the css the browser needs to parse the html, parse the css, link the two. A css rule may end up not even applying to any elements on the page if a particular selector has no matches. Only after all this can it begin downloading the actual images.

Using srcset/sizes the browser parses the html and can begin downloading the correct image variants immediately, before it parses css.

With prefetching enabled this means your browser could parse the html and cache all the image variants on the page that you'll need when hovering over a link to another page. So when you actually click on it everything is loaded from cache and super fast.

It's up the browser to manage situations of lower network speed, pixel density, etc. and to determine when and how much preloading to do. Using srcset/sizes just gives the browser the option to optimize as much as needed.

I think I understand what you are saying.

I did not consider the overhead of the browser parsing the CSS file and then figuring out which rules are applied where and depending on what rules are being applied, figuring out what else needs to be downloaded, etc.

But is that overhead really that significant? Or will the responsive images approach merely shave off a few % off the page load time?

While I think that the overhead on it's own might not be that much, even little gains of tens of MS can add up to improve the experience.

And something like srcSet will possibly allow the useragent to become "smarter" in the future. Perhaps halving image size when low on battery, or when on a limited mobile plan.

This isn't you choosing which image to serve who as a developer, it's serving up a bunch of options and letting the useragent choose which it knows is best for the user at that time.

In the case of preloading. The performance you're shaving off is all the time it takes to download all the images on your page. Which can be significant.

If you're on a slow connection, it can make a page load like it was loading from cache. Which can be quite significant compared to the css approach.

The question of whether the time spent implementing the feature is worth the benefits for a particular project / audience will vary on your use case.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact