开发者

Contextualizing jQuery

I've got a fairly large site, with a lot of jQuery code for lots of different pages. We're talking about 1000 lines of fairly well optimized code (excluding plugins).

I know jQuery is fairly good at ignoring listeners for page elements that don't exist, but it still has to test their existence when the page loads. I'm also creating a load of vars (including decent sized arrays and objects), but only a few of them are used on each page.

My Question is: What's the best method of cutting down the amount of work each page has to do?

However, I do NOT want to split up the code into separ开发者_Go百科ate files. I want to keep all my code in 1 place and for the sake of efficiency I only want to call the server to download JS once (it's only 30kb, smaller than most images).

I've thought of several ways so far:

  1. Put all my code chunks into named functions, and have each page call the functions it needs from inline <script> tags.
  2. Have each page output a variable as the pageID, and for each chunk of have an if statement: if (pageID = 'about' || pageID = 'contact') {code...}
  3. Give each page (maybe the body tag) a class or ID that can be used to identify the chunks that need executing: if ($('.about').length || $('.contact').length) {code...}
  4. Combine 1 and 2 (or 1 and 3), so that each page outputs a variable, and the if statements are all together and call the functions: if (pageID = 'about') {function calls...}

Any other ideas? Or which is the best/most efficient of those?


Your first option will be fastest (by a minute margin).
You'll need to remember to call the functions from the correct pages.

However, don't bother.
Unless you've measured a performance impact in a profiler, there is no need to optimize this much.


I would argue that you are taking more of a performance hit for downloading the 30k then you will ever see from the code execution. That said, you could always test your url to determine the page and run all setup methods through a bootloader that determines the correct functions to run/ events to bind at load time. Something like the following maybe:

$(function(){
  var page_methods = {
        home : [meth_1, meth_2],
        about : [meth_3, meth_2]
      },
      page = location.pathname.match(/\/(\w)$/)[1],
      i = 0,
      meth;

  for ( ; meth = page_methods[ page ][ i++ ] ; ){
    meth();
  }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜