How to load a .js-file depending on screen size?

How can we load a specific Javascript-file using the media queries from the WordPress themefolder (wp-content/themename/js/file.js)

Whe would only like to load grid.js when using a tablet or a desktop browser.

Related posts

Leave a Reply

1 comment

  1. You should load your grid.js asynchronous:

    function is_touch_device()
    {
              
      return !!('ontouchstart' in window);
               
    } 
    
    function loadGridJs() 
    {
    
      var scriptTag = document.createElement('script'); 
      scriptTag.src = "//wp-content/themename/js/grid.js"; 
      scriptTag.type = 'text/javascript'; 
      scriptTag.async = true;  
      var headTag = document.getElementsByTagName('head')[0];
      headTag.appendChild(scriptTag);
    
    }
    
    if (is_touch_device())
    {
    
      loadGridJs();
    
    } 

    See:

    Javascript asynchron nachladen,
    Touchgeräte erkennen