Responsive graphs with JavaScript and HTML
I could not get Chrome's Lighthouse tool to see my small responsive images.
Also, if I toggled the device to be a mobile then Chrome did not load in the smaller images meant for a mobile.
But if I simply shrunk the size of Chrome's pane which shows the page, then Chrome did load the responsive images.
I think the reason is that the mobile that Chrome simulates has an image density greater than 'one'. So Chrome wants a large image that 'shrinks' down into the image density.
I want to show the smaller images because the images are graphs and if a larger image is shrunk by the browser then the text becomes too small to read. I have redrawn most of my images specifically for smaller image sizes. It is easy to redraw images made with Gnuplot, but harder to redraw 3D graphs made with Excel.
I tried using a 'picture' tag rather than an 'img' tag. This is like 'art direction' where a completely different image is shown for different screen sizes. This worked in Chrome on an desktop but not in a simulator of a real mobile.
So I use JavaScript to get the screen width and set the images 'src' attributes to the appropriate image. I do this when the page loads and also when the window is resized.
For images that are not visible when the page loads, I only set the 'src' when the images become visible. I use an 'IntersectionObserver' for this.
The 'resize' event fires a lot, so I only set the 'src' if the size needs a new image. I am also going to try using 'throttling' or 'debouncing'. This uses a 'timeout' to avoid checking the page size too often.
I keep track of which images are visible so I can resize an image that is visible when the page is resized.
I kept 'loading="lazy"' on the images. So sometimes I set the 'src' but the image is only loaded later. Other times, an image is loaded just before the image is visible, and the the image of the right size is then loaded when the image becomes visible.
If the mobile browser is set to 'desktop view' then I use the real screen width which is available in 'screen.availWidth'.
But now Chrome's Lighthouse tool complains, saying the images have low resolution. This might affect the page's ranking in Google's search.
I keep a default large image on the 'img' tag. But this means mobiles have to load an extra smaller image when the page loads.
In one case, I wanted to have a narrow small image and a wider large image, but the aspect ratios needs to be the same to help the browser lay out the images. Lighthouse also complains.
So I am going to scale up the small image to be the larger image so Chrome then shrinks it back again. Hopefully, Lighthouse will not complain then. But I will have to make the small image less narrow or it will look too tall at larger sizes.

Comments
Post a Comment