Bud
Bud

Reputation: 1491

Loading jquery depending on window size

I am new to javascript and struggling with this basic problem - I want to load jQuery only if the window size is below a certain threshold (i.e., the mobile version doesn't require it). For the desktop version, jQuery must load in the <head> and not the <body>, as the content above the fold requires it.

I've tested the loop, and I'm getting the screen width printed on the page, but jQuery isn't loading. I'm sure it's a basic syntax problem but I just can't see it! Any help would be most appreciated. :)

   <script type="text/javascript"> 
        function loadjsfile(filename){
         var fileref=document.createElement('script');
         fileref.setAttribute("type","text/javascript");
         fileref.setAttribute("src", filename);
         }

        var w=window.innerWidth
        || document.documentElement.clientWidth
        || document.body.clientWidth;
            if (w > 899){
                document.write("screen Width: " + w);
                loadjsfile("http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js");
                }
   </script>

Upvotes: 1

Views: 56

Answers (1)

scunliffe
scunliffe

Reputation: 63588

you've created the fileref variable that contains your script tag object but you never add it to the DOM, thus it never loads.

function loadjsfile(filename){
    var fileref = document.createElement('script');
    fileref.setAttribute("type","text/javascript");
    fileref.setAttribute("src", filename);

    //add this line
    document.getElementsByTagName('head')[0].appendChild(fileref);
}

Upvotes: 2

Related Questions