Home > Software design >  How to load script only on desktop and tablet using javascript
How to load script only on desktop and tablet using javascript

Time:03-30

I want the following code to load only on desktop and tablet.

<script type="text/javascript" src="//wcs.naver.net/wcslog.js"></script>

Referring to this comment, I saved the code below as example.js and loaded it from the header.

$( document ). ready(function() {
     var isMobile = window.matchMedia("only screen and (min-width: 600px)");

     if (isMobile.matches) {
        **<script type="text/javascript" src="//wcs.naver.net/wcslog.js"></script>**
     }
  });

But the script does not loaded.

I'd like to hear some advice on how I should fix it.

Thank you

CodePudding user response:

Maybe the wp_is_mobile() function could help: https://developer.wordpress.org/reference/functions/wp_is_mobile/

I mean you can wrap the script tag within this condition and do it via PHP directly.

  • Related