74

I need a JS statement that determine which JavaScript file to use.

I have one file:

<script type="text/javascript" src="js/jquery_computer.js"></script>

But when the screen width is less than 500px, I want load another file instead:

<script type="text/javascript" src="js/mobile_version.js"></script>

I have tried everything and it is not working.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user2190308
  • 761
  • 1
  • 5
  • 4

8 Answers8

74

You'd have to create that markup yourself in JS. Something like this:

var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");

js.type = "text/javascript";

if (screen.width > 500)
{
    js.src = "js/jquery_computer.js";
}
else
{
    js.src = "js/mobile_version.js";
}

head.appendChild(js);
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • 1
    I like this approach. And sometimes a script will fail to load so this concept of polling to see if your script made it can be useful http://stackoverflow.com/questions/1130921/is-the-callback-on-jquerys-getscript-unreliable-or-am-i-doing-something-wrong#answer-1131018 – Dylan Valade Jun 18 '15 at 20:32
  • Mind that with screen.width on a desktop with a reduced browser window it will still give you the device width, not the actual space available. Depending on scenario you can use the built-in window.matchMedia (cf my answer) or keep screen.width – fadomire Sep 15 '15 at 13:11
  • Related: https://stackoverflow.com/questions/48069951/how-to-load-javascript-source-from-the-working-directory-of-the-current-source-f –  Jan 03 '18 at 01:16
37

If you want the script loaded asynchronously, the other answers here do that.

If you want it loaded synchronously with page load, this is one of the very, very few remaining valid uses cases for document.write:

<script>
(function() { // Scoping function to avoid globals
    var src = /*you want the main version*/ ? "jquery_computer.js" : "mobile_version.js";
    document.write('<script src="js/' + src + '"><\/script>');
})();
</script>

(I've removed type because JavaScript is the default, specifying it isn't useful.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 4
    Perfect for the `if (typeof Promise === 'function') {/*load a script */}` use case needed to work around microsoft's "Compatibility Solution." – O. Jones Jun 14 '19 at 13:30
12

Maybe you can use matchMedia.js and can load a script using jQuery.getScript

$(function(){
    if (matchMedia('only screen and (max-width: 500px)').matches) {
        $.getScript(...);
    }
});
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • I prefer a solution that doesn't depend on jQuery. I'm currently using YepNope (http://yepnopejs.com/) but I'd like to replace it with another solution considering the library's been deprecated by the author. – John Slegers Mar 21 '15 at 14:11
11

Best would be to use built-in matchMedia API.

var script = document.createElement('script');
script.type='text/javascript';

if(window.matchMedia("(min-width:500px)").matches) {
  script.src = 'js/jquery.slitslider.js';      
}else{
  script.src = 'js/mobile_version.js';      
}

document.getElementsByTagName('head')[0].appendChild(script);

Drawback is that it is not supported in IE < 10

fadomire
  • 1,865
  • 1
  • 15
  • 23
7

You don't need jQuery for this, it suffices to create the <script> tag in the DOM dynamically:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');

script.type = 'text/javascript';

if (<screen-width less than 500>)
    script.src = "js/mobile_version.js";
else
    script.src = "js/jquery_computer.js";

head.appendChild(script);
filmor
  • 30,840
  • 6
  • 50
  • 48
3
$(function(){
    var width = $(document).width(),
        mobile = 500;

    if (width > mobile) {
        $('head').append('<script class="desktop" type="text/javascript" src="js/jquery_computer.js"></script>');
        $('head').find('.mobile').remove();
    } 
    else
    {
        $('head').append('<script class="mobile" type="text/javascript" src="js/mobile_version.js"></script>');
        $('head').find('.desktop').remove();
    }
});

just use if else to detect condition and use class on script element may be it help

user3755768
  • 67
  • 1
  • 6
2

You could use the async import() if you like.

import(condition ? 'js/desktop_version.js' : 'js/mobile_version.js')

In a script tag with <script type="module"> or inside a module loaded with import() from a regular <script> you can also use top-level await in the newest (experimental) browsers

<script type="module">
  await import(condition ? 'js/desktop_version.js' : 'js/mobile_version.js')      
</script>

But it won't work for every script.

  • A common reason why is those UMD module bundler that adds a closure
    (function(global){...}(this)) since this is undefined in modules.
  • Third party scripts needs to have CORS enable to load
  • Won't work in IE, but it's dead anyway
  • See other known differences
Matze
  • 361
  • 4
  • 9
Endless
  • 34,080
  • 13
  • 108
  • 131
1

you can use $.getScript in jQuery

see here for details

PSR
  • 39,804
  • 41
  • 111
  • 151