Search code examples
javascriptjqueryscreen-size

How to include a JavaScript file when the screen is a certain size?


I want to include a file such as foo.js, only when the screen is a certain size.

For example:

<script>
if (screen.width <= 960)
{
    document.write('\x3Cscript type="text/javascript" src="/foo.js">\x3C/script>'); 
}
</script>

Any ideas?


Solution

  • Append the script to the head, don't use document.write

    <script type="text/javascript">
    
        if (screen.width <= 960) {
           var head    = document.getElementsByTagName('head')[0];
           var script  = document.createElement('script');
           script.type = 'text/javascript';
           script.src  = '/foo.js';
           head.appendChild(script);
        }
    
    </script>