Page 1 of 2 12 LastLast
Results 1 to 10 of 20

Thread: load jQuery in functions or footer

  1. #1
    curtismchale is offline Hello World
    Join Date
    Dec 2009
    Location
    BC, Canada
    Posts
    38

    Default load jQuery in functions or footer

    I was working on my base theme recently and realized that I was breaking a major rule in site opitmization, I was loading my jQuery in the header which is bad. I've actually been using the method described by Chris and Jeff here: http://digwp.com/2009/06/use-google-...the-right-way/

    I was headed to change it and was wondering what the benefits/detriments are to loading the JS out of the functions file or just put the call to Google libraries in the footer? Anyone have knowledge/thoughts?

  2. #2
    Ryan's Avatar
    Ryan is offline WordPress Legend
    Join Date
    Jan 2009
    Location
    New Zealand
    Posts
    2,801

    Default

    You should always load your scripts via the enqueue method (ie: as Chris Coyier suggested) because it allows other plugins to modify the hook content when they need to and allows them to know if jQuery etc. are loaded already or not.

    You can load scripts in the footer via wp_enqueue too as of WordPress 2.8 ... http://lesterchan.net/wordpress/2009...-wordpress-28/

    There are good reasons to load the JavaScript in the header some times though, particularly for mission critical things which need to load early on during the page load process.

  3. #3
    Ryan's Avatar
    Ryan is offline WordPress Legend
    Join Date
    Jan 2009
    Location
    New Zealand
    Posts
    2,801

    Default

    This sort of thing is not uncommon to see in the footer of a page to trigger the Suckerfish script to allow hover menus to work in IE6:
    Code:
    <script type="text/javascript" src="http://domain.com/suckerfish_ie.js"></script>
    That tends to be infuriating as it means that the menu is totally useless until the entire page and it's content, scripts etc. have loaded. So fundamentally important scripts like that need to go at the top between your <head> tags (and in this particular case, inside IE7 conditional comments too).

  4. #4
    Rarst's Avatar
    Rarst is offline Big Tipper
    Join Date
    Jul 2009
    Posts
    322

    Default

    I was just setting up scripts in new theme on development stack. Highly useful tutorial on topic by scribu.

    Current version:

    PHP Code:
    add_action('init''restatement_jquery_register');
    add_action('wp_footer''restatement_footer_scripts');

    function 
    restatement_jquery_register() {
        if (!
    is_admin()){
            
    wp_deregister_script('jquery');
            
    wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"), false'1.4.2',true);
        }
    }

    function 
    restatement_footer_scripts() {
        if (!
    is_admin()){
            
    $js='/js/restatement.js';
            
    wp_register_script('restatement'get_stylesheet_directory_uri().$js,array('jquery'),filemtime(STYLESHEETPATH.$js),true);
            
    wp_print_scripts('restatement');
        }

    In init hook I change jquery definition from WP-bundled to Google CDN. Also last parameter tells it to load jquery in the footer, unless other script demands it earlier.

    In footer I enqueue my theme's script (or more), version it with file modification time and set dependency on jquery. Since I output it explicitly I can also override this somewhere in the page if needed (regular way enqueues scripts much earlier).

    Result in footer:
    Code:
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js?ver=1.4.2'></script>
    <script type='text/javascript' src='http://localhost/wordpress/wp-content/themes/restatement/js/restatement.js?ver=1266935793'></script>
    Only thing I hadn't figured out is how to prevent WP from putting version tag on jquery from Google - it is harmful in that case.

    PS might also need to tweak priority on hooking jquery register so it is fired early enough
    Last edited by Rarst; 02-26-2010 at 12:22 AM.
    Rarst.net - cynical thoughts on software and web (and sometimes WP) | @Rarst | I seem to be non-GPL-compliant person. Beware my poisonous thoughts.

  5. #5
    Otto's Avatar
    Otto is offline On The Rocks
    Join Date
    Apr 2009
    Location
    Memphis, TN
    Posts
    865

    Default

    My personal feelings on the topic:

    - Loading library scripts in the footer is overrated. Put your script in the header and trust in the power of the cache.

    - Don't add special code to screw with scripts like this. Just do simple, normal enqueues and be done with it.

    - If you want to use Google hosted libraries, use the plugin that does it for you in the right way. Unlike the ways mentioned above, this:
    a) works over the whole site (admin too)
    b) it works correctly (without the version tagging),
    c) it handles issues like the noConflict mode properly, and
    d) it doesn't make your plugin all complicated to where it will interfere with other plugins.

    Rolling your own code to do this in a half-assed way is A Bad Idea (tm). Separate the workload off into specialized pieces designed specifically to handle the task properly. You get maximum benefit this way.

  6. #6
    curtismchale is offline Hello World
    Join Date
    Dec 2009
    Location
    BC, Canada
    Posts
    38

    Default

    @Otto

    I really think that the JS library is theme dependant and I shouldn't be relying on a plugin. What if the user doesn't install it?

    As for loading scripts in the footer vs header I think that there is lots of research out there that shows the footer is the way to go. Each script file loaded in the header blocks all other downloads so you're not using the mutli-threaded downloading that browsers are capable of. Sure most small sites will see very little benefit in footer vs header but the right way is the right way.

    @Ryan

    Yeah I knew that enqueue should be used I was wondering if anyone had info on whether loading it out of the functions file or in the footter with enqueue was a faster way to do it. Guess I'll run my own speed tests on it at some point.

    I'm on board with loading JS conditionally for IE if needed for sure. I've not encountered any other time that JS could in any fashion be considered 'mission critical.' JS should just be the extra functionality on the site. It should still function without JS at all so I don't see how it could be mission criticial (outside IE as mentioned).

    @Rarst

    Thanks for the code I'll take a dig through it later today. Why is the version tag harmful in the JS? Are we just worried about hackers knowing which version or will plugins be looking for a specific version?

  7. #7
    Otto's Avatar
    Otto is offline On The Rocks
    Join Date
    Apr 2009
    Location
    Memphis, TN
    Posts
    865

    Default

    Quote Originally Posted by curtismchale View Post
    @Otto
    I really think that the JS library is theme dependant and I shouldn't be relying on a plugin. What if the user doesn't install it?
    jQuery is built into WordPress. All you have to do to load it is wp_enqueue_script('jquery');

    If you do that, then jQuery loads. It's not theme dependent in the slightest.

    Now, if somebody wants to optimize their site by loading jQuery from Google, then they can load the plugin. If not, then they won't. But you making your plugin have a dependency on google, as well as having it break *my* plugins which load jQuery the proper way and don't expect your weird changes... That doesn't seem all that bright.

    BTW, not everybody can load javascript libraries from Google. WordPress is used on internal sites too, you know. Consider all possible audiences for your plugin.

    Quote Originally Posted by curtismchale View Post
    As for loading scripts in the footer vs header I think that there is lots of research out there that shows the footer is the way to go.
    Yes. It's all wrong too.

    Here's the thing about people who research this sort of thing: They never look beyond the load time of a single page. Sites consist of more than one page, and seeing how fast a single page loads is useless in determining the speed of a site.

    Quote Originally Posted by curtismchale View Post
    Each script file loaded in the header blocks all other downloads so you're not using the mutli-threaded downloading that browsers are capable of.
    And if you're loading jQuery from Google using that plugin I pointed you to earlier, then you're not downloading anything whatsoever, because your browser has it cached from some other site that's using it.

    Even if you're not, if you're loading it up on every page on the site, then it's cached from the first time it got loaded. So on subsequent loads, there's no HTTP request of any kind at all. No delay whatsoever.

    Quote Originally Posted by curtismchale View Post
    Sure most small sites will see very little benefit in footer vs header but the right way is the right way.
    No real site will ever see any benefit from this sort of thing, ever. And by "real", I mean, "not contrived by some deluded fool who is doing 'research' into page load speeds".

    Theory is theory, but reality is reality. And the theory here is poorly thought through, because it is only considering a tiny fraction of a subset of real world internet browsing behaviors.

    Quote Originally Posted by curtismchale View Post
    Why is the version tag harmful in the JS?
    It breaks browser caching. That's why it's there, in fact. However, in this case, we want long term browser caching from other sites.

  8. #8
    Otto's Avatar
    Otto is offline On The Rocks
    Join Date
    Apr 2009
    Location
    Memphis, TN
    Posts
    865

    Default

    BTW, there's a term for this sort of notion: Premature Optimization.

    Donald Knuth said it best:
    "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

    Small optimizations don't matter until they actually matter. If you're serving terrabytes of data a day, then yes, knocking off a few bytes or milliseconds makes a big difference. But if you're serving only a few thousand requests a day, then it just doesn't matter.

    Saving 10 milliseconds but breaking compatibility with, say, 3% of plugins is a bad tradeoff. That 10 milliseconds is only ever going to actually matter to a tiny fraction of a percent of websites. And they know who they are, and they can optimize themselves when it's necessary.

    The proper way to "optimize" is to profile first. Find the places where the effort you expend makes the most impact. If you're *ever* optimizing without having first profiled your total system in detail, then you're doing it wrong.

    Premature optimization is bad because it actually hides real places where performance can be improved. Optimization, of any sort, always involves making things more complicated. It is easier to profile a system that is simple and elegant, and this can lead you to major performance improvements first. If you spend a bunch of time optimizing stuff that doesn't fundamentally matter, then not only have you wasted your time, but you have also made it that much more difficult to find the real bottlenecks in the system as a whole.

    Yes, profiling is hard. That doesn't mean you shouldn't do it first. Always write the code in a simple and elegant way. Only optimize that code once you've determined which parts of that simple and elegant design are the real time sinks.
    Last edited by Otto; 02-26-2010 at 01:10 PM.

  9. #9
    Ryan's Avatar
    Ryan is offline WordPress Legend
    Join Date
    Jan 2009
    Location
    New Zealand
    Posts
    2,801

    Default

    Quote Originally Posted by curtismchale View Post
    Yeah I knew that enqueue should be used I was wondering if anyone had info on whether loading it out of the functions file or in the footter with enqueue was a faster way to do it. Guess I'll run my own speed tests on it at some point.
    If there is a difference, then it would be tiny I assume.

    Quote Originally Posted by curtismchale View Post
    I've not encountered any other time that JS could in any fashion be considered 'mission critical.' JS should just be the extra functionality on the site. It should still function without JS at all so I don't see how it could be mission criticial (outside IE as mentioned).
    I guess that all depends on how you define "mission critical".

    There's nothing worse than loading a web-page, then after you've started reading the content, everything starts flying all over the page coz some stupid JS file is moving it around. I find this is particularly problematic with the featured galleries which many people (myself included) use on their home pages. This seems to be a particularly annoying problem when the JS is loaded in the footer as the entire page may have loaded before that JS file which aligns all the images in the featured gallery is executed.

  10. #10
    curtismchale is offline Hello World
    Join Date
    Dec 2009
    Location
    BC, Canada
    Posts
    38

    Default

    @Otto

    I'd be interested to know why the research that shows loading scripts in your footer is wrong. All of the items I have read on it acknowledge that they are looking at single page load and ignoring caching. Even if we only look at single page load it's still faster for people visiting your site the first time to get to actual content.

    From everything I've read and all of the developers I've talked to they would not say that this is premature optimization. They'd say it just the right way to do it. For the minimal time it takes to load JS properly in the footer it's not like we're spending hours working on it and it's becoming a huge time sink. Further when a theme ends up getting used on a huge site that would be transferring huge amounts of data we're already loading the scripts properly for speed so it's something we don't need to do later.

    Also I'm not sure how I'd be breaking plugin compatibility if I'm using the enqueue script properly as I plan to do.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •