is there a way to preload specific images for desktop users only? (excluding mobile users)

My website has a few .PNG images animated at the very start of my Contact page. Those images are a bit heavy (because they have transparent background), so the animation starts with some of them loading during the animation, looking pretty bad.

So, to fix it, I must add this line link rel=preload as=image href=url-of-the-image.png/ to the head.

To achieve it, I'm using Snippets plugin. If I'm not mistaken, the snippet should like this:

add_action( 'wp_head', function () { ?

function my_custom_js() {
    echo 'link rel=preload as=image href=href=url-of-the-image.png/';
}

?php } );

The thing is that the very same page (my Contact page) is different for mobile devices: it doesn't use those .PNG images because it would be too much loading time for a phone.

This leads to my question: Is there a way to exclude mobile devices from the preloading tag I must add to the head?

Topic responsive wp-head plugins Wordpress performance

Category Web


Ok, so I ended up using "prerender" instead of "preload" because it suited my circumstances (prerender starts rendering target page before the user visits it, in my case it was a better fit because the page I wanted to preload was not the front-page).

For anyone who's interested in knowing about the responsiveness of preloading or prefetching, the property "media" is what you're looking for. It should look like this:

<link rel="preload" as="image" href="imageURLhere.png" media="(min-width: 768px)"/>

...or if you want to target a whole page to pre-render:

<link rel="prerender" href="targetPageURL/" media="(min-width: 768px)">

This way it should only preload or prerender if the viewport is within the media conditions range.

Hope it helps! Cheers


You can use wp_is_mobile() to check whether it is a mobile device or desktop user.

<?php if ( wp_is_mobile() ) : ?>
    /* Display and echo mobile specific stuff here */
<?php else : ?>
    /* Display and echo desktop stuff here */
<?php endif; ?>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.