Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect browser support for "picture" element

As part of updating my website to be more mobile friendly I need to serve up different images based on screen/browser size. I've come across using the "picture" element which works great when it's supported. The problem at this time is that it's not supported everywhere. I'd like to detect if the "picture" element is supported by the browser so I can fall-back to a different method.

How can I detect if the "picture" element is supported by the browser?

Since this is the only type of check I currently need, I'd like to avoid pulling in a library (ex. Modernizr) if possible.

like image 794
codesniffer Avatar asked Dec 05 '22 02:12

codesniffer


1 Answers

Finding out if picture is supported is actually quite simple:

var pic = !!window.HTMLPictureElement;
console.log("picture supported: " + pic);

This will print false if your browser needs a workaround or true if it supports picture. Clearly it doesn't necessarily mean that support for picture is also complete and great (and as of early 2016 it's probably still work in progress in many browsers).

Regardless of the picture element having a fallback built-in, I believe there are legitimate reasons for wanting to know whether a browser supports the picture element or not.

For example you might want to provide your own workaround instead of using something massive like the picturefill.js polyfill.

like image 161
duncanwilcox Avatar answered Dec 09 '22 13:12

duncanwilcox