Archived topic
How to prevent javascript from loading on mobile devices
5 replies · Started by Roland on March 23, 2018
Hi there,
in >GP Hooks >wp_footer I load some JS to animate my site. On mobile devices, I don't want that JS files to be loaded, because they destroy the layout a little bit.
How can i prevent the JS files from being loaded on a mobile device?
In the case of css files I know that I can write the following:
<link rel="stylesheet" media="(min-width: 672px)" href="abc.css" />
Is there such a thing for JS files too? For the expression <script ... ></script>
Probably it works with PHP or a media query in JS - but I don't know PHP and JS. Can I say with HTML that JS files should only be loaded on large screens? I didn't find anything on the Internet.
Roland
Here is an example:
<script>
jQuery(document).ready(function($){
if($(window).width() > 1024){
$(window).scroll(function(){
$(".scrolleffect").css("opacity", 1 - $(window).scrollTop() / 650);
$(".scrolleffect2").css("opacity", 1 - $(window).scrollTop() / 325);
$(".scrolleffect2b").css("opacity", 1 - $(window).scrollTop() / 350);
});
}
});
</script>
Hi Gábor,
Thank you for your answer.
I downloaded a JS file from the Internet. Let's call it abc.js. I integrate this file into my page via >GP Hooks >wp_footer. The file has 482 lines. Should I edit this file and wrap the complete content? Like this?
if($(window).width() > 768){
.
.
.
482 lines
.
.
.
}
I'm looking for a way to prevent the file from loading at all...
Javascript doesn't have media queries unfortunately, so I don't believe this is possible.
The actually javascript inside the file would need to be altered to only apply on desktop, using a similar method to what Gábor wrote.
Hi Tom,
Thank you for your answer.
Then I can stop my search now...
Thanks for your help
Roland
No problem!