Different attribute values for an HTML element based on responsiveness

This is really a server-side solution and not using CSS's media queries

There was a situation where I need to set the width and height attributes of an image without the CSS, since I was setting the CSS height via TailWindCSS's classnames based on responsiveness - h-9 sm:h-20 - h-9 for mobile view and h-20 for desktop view. Because Setting Height And Width On Images Is Important Again for Google's PageSpeed Insights, I had to set the width and height attributes of the HTML img element on the server side, using PHP.

detectmobilebrowsers has real short insert-able snippets for almost every web language. For PHP, its at detectmobilebrowsers.com/download/php

You'll get a 3 line code like below - the regular expression is not included in this post as it's too long.

Include this in your base php file :

<?php
$useragent=$_SERVER['HTTP_USER_AGENT'];
if(preg_match('/this is a very long regular expression/i',substr($useragent,0,4)))
    $GLOBALS['isMobile'] = true;
?>

Then, in the HTML file you can set the width and height attributes :

$dimensions = 'width="80" height="80"';
if (isset($GLOBALS['isMobile']) && $GLOBALS['isMobile'])
    $dimensions = 'width="36" height="36"';

Now my img tag in my HTML looks like this :

<img class="h-9 sm:h-20" src="https://my-bucket.amazonaws.com/images/my-image.webp" alt="my image" <?php echo $dimensions ?> />

Now Google PageSpeed Insights won't complain of images without dimensions.