Ad

Load Script Only If Window Is Larger Than X

- 1 answer

I am currently using the script below, but noticed that it only works with screen size, not window size, so resizing the browser does not trigger it. How can I get this to run only when the screen size is larger than X? Are there any consideration that I should take into account for retina displays?

<script>
if (screen && screen.width > 899) {
document.write('<script async type="text/javascript" src="http://example.com/myscript.js"><\/script>');
}
</script>
Ad

Answer

This can be accomplished with window.matchMedia (docs)

<script>
  var mediaQuery = window.matchMedia('(min-width: 400px)');

  mediaQuery.addListener(loadScripts);

  function loadScripts() {
    document.write('\x3Cscript src="myScript.js">\x3C/script>');
  }    
</script>

<script src="mySecondScript.js"></script>
<script src="myThirdScript.js"></script>

Here's a JSFiddle.

Ad
source: stackoverflow.com
Ad