Question

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?

Was it helpful?

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>

OTHER TIPS

Using jQuery, try this:

if ($(window).width() <= 960) {     
    document.write('\x3Cscript type="text/javascript" src="/foo.js">\x3C/script>');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top