0
votes

Just a quik question about the right syntax. I want to load the jquery file only if the browser screen is < 1100px.

<script type="text/javascript">
$(document).ready(function() {
  if ($(window).width() < 1100) {

    //load file

     }
  });
</script>

I want to load src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js but can't find the syntax.

Thanks!

2
Are you loading jQuery based on a condition you calculated using jQuery? - David Hellsing
yes :) I hava another version of jquery loaded. But it is just a problem with the 1.5.1 version which is in conflict with some other. Basically some code (which I use in the version for smaller screens) is not working while this version of jquery is loaded. - Claudiu Creanga

2 Answers

1
votes
$(document).ready(function() {
    if ($(window).width() < 1100) {
       var newscript = document.createElement('script');
           newscript.type = 'text/javascript';
           newscript.async = true;
           newscript.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js';
       (document.getElementsByTagName('head')[0]
        || document.getElementsByTagName('body')[0]).appendChild(newscript);
    }
});
2
votes

I assume you don’t have jQuery when you are trying to fetch the window width, so something like this:

<script>
    var width = window.innerWidth || document.documentElement.clientWidth;
    if ( width < 1100 ) {
        var s = document.createElement('script'),
            p = document.getElementsByTagName('script')[0];
        s.async = true;
        s.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js';
        p.parentNode.insertBefore(s, p);
    }
</script>

If you have jQuery, it’s a bit simpler syntax:

<script>
if ( $(window).width() < 1100 ) {
    $('<scr'+'ipt>').attr({
        src: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
        async: true
    }).insertBefore($('script:first'));
}
</script>

I don’t think you will "unload" a version of jQuery by loading another lower version, but that is your call :)