0

My site has a jQuery zoom feature that is crashing on tablets. I think my best approach is to just remove it - it's not necessary. So I'd like to not have it load if the viewport is less than 980px, what can I do to this code to do that?

<script src='js/jquery.zoom.js'></script>

something like <script>if viewport > 980px load 'script.js'</script>?

Ghost Echo
  • 1,997
  • 4
  • 31
  • 46
  • 1
    These may be helpful: http://stackoverflow.com/questions/7111131/best-way-of-dynamic-script-loading http://stackoverflow.com/questions/3044573/using-jquery-to-get-size-of-viewport – Josh Mein Sep 04 '13 at 14:17

2 Answers2

1

Use the AJAX function $.getScript():

if ($(window).width()>980) {
    $.getScript('js/jquery.zoom.js');
}

or simply write out the HTML, if you want it to load synchronously:

if ($(window).width()>980) {
    document.write("<script src='js/jquery.zoom.js'></script>");
}
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • These both seem to interfere with the other javascript on the page. I can't seem to place it right or even get it to work... – Ghost Echo Sep 04 '13 at 17:54
  • Can't help you there; you haven't shared the other JavaScript on the page. – Blazemonger Sep 04 '13 at 18:15
  • It's got alot of jquery. The site functions fine with just the `` in it, but changing it to your suggestions messes everything up. Is `document.write` getting loaded before my functions using `document.load`? – Ghost Echo Sep 04 '13 at 18:18
  • I mean, shouldn't I be able to just swap out my line for your lines? Isn't it still being executed in the same order? – Ghost Echo Sep 04 '13 at 18:19
  • Again, I can't answer those questions without actually seeing the rest of your code. – Blazemonger Sep 04 '13 at 18:21
  • I see. I think this is my problem: This script is for an image zoomer that uses the
    's ID like so: `` I think this is being executed before the call you suggested...should I try setting a delay on it?
    – Ghost Echo Sep 04 '13 at 18:25
  • Probably that code is running before your plugin is downloaded. Why don't you try downloading the plugin all the time, and running the `.zoom()` method only if the browser is wide? – Blazemonger Sep 04 '13 at 18:27
  • Sometimes it has multiple instances such as `` could I still do that? – Ghost Echo Sep 04 '13 at 18:28
  • Yes, but you should probably be using a common class instead of zooming each ID individually. – Blazemonger Sep 04 '13 at 18:34
  • By Jove that did the trick. Great idea man, thanks so much. BTW, I think I need have the ID's be clicked on and not classes, that's the way the image zoomer is set up. (http://www.jacklmoore.com/zoom/) But thank you so much! – Ghost Echo Sep 04 '13 at 18:44
1

how about:

 $(document).ready(function(){
        if(viewport>980){
            $.getScript('script.js');
        }
    });
roullie
  • 2,830
  • 16
  • 26