开发者

load scripts conditionally at end of document

I want to load jquery and cycle plugin only if window is certain size. this will be changed later to load only for desktop browsers. if I place this code before the closing body tag, it works fine in FF and IE, but not in chrome. if I place the code in the head, it works in all browsers. how can I get it to work when placed at the end of the document?

http://dl.dropbox.com/u/426954/allora/index.html

  if (document.documentElement.clientWidth > 600) {
    window.onload = function() {
    //load jquery
      var j = document.开发者_StackOverflowcreateElement('script');
    j.setAttribute( 'src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js');
    document.getElementsByTagName("head")[0].appendChild( j );

    //load cycle plugin
      var c = document.createElement('script');
    c.setAttribute( 'src', 'http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js');
    document.getElementsByTagName("head")[0].appendChild( c );

    //load custom script
      var elScript = document.createElement('script');
    elScript.setAttribute( 'src', 'js/script.js');
    document.getElementsByTagName("head")[0].appendChild( elScript );
    }   
    }


So just place it in the head. Just because performance guidelines ask you to put them at the bottom of the script doesn't mean that it's a sin to put them in the head. in this case, you won't be losing any performance because all it does is assign a handler to the onload event, which will wait until the DOM is loaded to run anyways


use this

$(document).ready(function() {

});

instead of

window.onload

and put "if" into function

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜