Outliners
Outliners

Reputation: 11

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.

Upvotes: 1

Views: 62

Answers (1)

Daschmi
Daschmi

Reputation: 56

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

Upvotes: 1

Related Questions