简体   繁体   中英

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?

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>

Using jQuery, try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM