Archived topic
Defer JS on Mobile only
6 replies · Started by Adrian on May 12, 2021
Is there any way to use GP Elements or code in functions or other places to defer JS for mobile devices only?
What I want exactly is the below code in wp_head only on mobile devices.
<script defer src=".js"></script>
Thanks.
Hi there,
You can use Elements to add your own <script> with the defer attribute - but it cannot filter a script that is being added by another plugin or function.
Most optimization plugins will do that for you.
I know the <script> code that I have to add.
But how do I add it for mobile-only in the meta(wp_head)?
Thanks.
Being a meta tag I can't use the hide-on-mobile attribute.
You can wrap the script in the wp_is_mobile function:
<?php
if ( wp_is_mobile() ) {
?>
// Your script here
<?php
}
?>
Note - if you're server has page caching you need to check if it supports cache splitting for mobile and desktop. If not a standard Page Cache 'may' cache the desktop version and then that code will never load.
The alternative would require using JS within your script to determine the screen width and only execute the code on the given condition.
Thank you.
You're welcome