There was a situation where I need to set the
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
height attributes of the HTML
img element on the server side, using 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 :
'HTTP_USER_AGENT']; if(preg_match('/this is a very long regular expression/i',substr($useragent,0,4))) $GLOBALS['isMobile'] = true;$useragent=$_SERVER[
Then, in the HTML file you can set the
height attributes :
$dimensions = 'width="80" height="80"'; if (isset($GLOBALS['isMobile']) && $GLOBALS['isMobile']) $dimensions = 'width="36" height="36"';
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" echo $dimensions />
Now Google PageSpeed Insights won't complain of images without dimensions.