Skip to content

JQuery Global Scope

August 15, 2012

Lately I’ve been working on a few plugins for JQuery, including one that allows methods in classic ASP.Net 1.1 web pages to be accessed through the JQuery $.ajax() call.  I had to do some pretty heavy research for that project, and along the way I came across a lot of examples on the web that make inefficient use of the JQuery selectors, and I felt inspired to share a method I’ve been using to cut down on some of my processing overhead.

Speaking from the perspective of processing and load time, selectors in JQuery are very expensive operations.  To try to counteract that, I’ve imposed a limitation on myself that I will never repeat a JQuery selection operation on the same page.  In other words, I’ll never do this:

$(".someClass").css("display", "true");
$(".someClass").css("border", "1px solid black");
$(".someClass").bind("click", function(){ ... });

Instead, I save the results of the selector to a variable first, like this:

var jClassObjects = $(".someClass");
jClassObjects.css("display", "true");
jClassObjects.css("border", "1px solid black");
jClassObjects.bind("click", function(){ ... });

Before I move on, I want to give an you an idea of how much of an impact this can have, I used FireBugz and Fiddler to evaluate performance on a test page that I created.  The page contained an unordered list with 100 items, each flagged with the .listItem class.

According to FireBugz, the following operation took 674 milliseconds to complete:

var jCollection = $(".listItem");

That means that if I performed the selection each time, as on my first example above, those three operations whould spend more than one and half seconds of processing time just to run the selections.  If I store the results in a variable, I save that 674 millisecond delay for every operation I perform.

Even better, though, is to take this one step further and start storing your variable within the global scope.  This has the advantage of making your selections available to other parts of your code.  Here’s an example, using the window object because it is already at the global level:

window.toolBox = {
	// run the selections you expect to use on the page
	body : $("body"),
	listItems : $("li"),
	classItems : $(".someClass")

function handleEvent() {
	// use the toolbox reference
	toolBox.listItems.css("background-color", "green");

You can also continue to add new selections to the global scope from other areas of your code:

function handleEvent() {
	// store the div elements within our toolbox
	toolBox.allDivs = $("div");
	// now I can reference both the old and new selection results
	toolBox.allDivs.bind("click", function() { alert('Click'); });
	toolBox.listItems.css("background-color", "red");

The JQuery library makes so many of our client-side tasks very simple, and I think one side-effect of that simplicity is an apathetic approach to performance and efficiency, so it’s important to keep tips like these in mind to help improve the user experience.

44 Comments leave one →
  1. March 6, 2014 9:01 am

    Pretty great post. I just stumbled upon your weblog and wanted to mention that I’ve really enjoyed browsing your weblog posts.
    In any case I will be subscribing for your feed and I am hoping you write once more
    very soon!

  2. March 7, 2014 12:22 pm

    I was recommended this website by my cousin.
    I’m not sure whether this post is written by him as nobody else know such detailed about my
    trouble. You’re wonderful! Thanks!

  3. March 8, 2014 7:34 am

    An intriguing discussion is definitely worth comment.
    I believe that you need to publish more about this issue, it might not be a taboo matter but typically people
    don’t speak about such issues. To the next!
    Many thanks!!

  4. March 10, 2014 1:57 am

    I’ve been surfing online more than 3 hours as of
    late, but I never found any fascinating article
    like yours. It’s beautiful worth sufficient for me.
    In my opinion, if all website owners and bloggers made good
    content material as you probably did, the web shall be much more useful than ever before.

  5. March 10, 2014 12:13 pm

    Hi are using WordPress foor your site platform? I’m new to the blog world but I’m trying to get started and create my own.
    Do you need any coding knowledge to make your own blog?
    Any help would be greatly appreciated!

  6. March 12, 2014 8:47 am

    Great beat ! I wish to apprentice while you amend your
    site, how can i subscribe for a blog site? The account helped me
    a acceptable deal. I had been a little bit acquainted
    of this your broadcast provided bright clear idea

  7. March 12, 2014 9:31 am

    It’s a pity you don’t have a donate button! I’d
    certainly donate to this superb blog! I suppose for now i’ll settle
    for bookmarking and adding your RSS feed to my Google account.
    I look forward to new updates and will talk about this website with my Facebook group.
    Talk soon!

  8. March 16, 2014 8:53 pm

    I take pleasure in, lead to I discovered just what I used to
    be looking for. You’ve ended my 4 day long hunt! God Bless you man.
    Have a great day. Bye

  9. March 17, 2014 1:03 pm

    It’s really a nice and helpful piece of info. I’m happy
    that you just shared this helpful information with us.
    Please stay us informed like this. Thanks for sharing.

  10. March 21, 2014 12:42 am

    Thanks to my father who shared with me regarding this weblog, this webpage is in fact awesome.

  11. March 21, 2014 5:32 pm

    When some one searches for his required thing, therefore he/she
    needs to be available that in detail, thus that thing is maintained over here.

  12. March 22, 2014 5:25 pm

    Good post however , I was wondering if you could
    write a litte more on this topic? I’d be
    very grateful if you could elaborate a little bit further.

    Appreciate it!

  13. March 26, 2014 12:20 pm

    Good day very cool site!! Man .. Beautiful .. Superb ..
    I will bookmark your blog and take the feeds also?
    I am satisfied to search out a lot of useful information right here in the put
    up, we’d like develop more strategies in this regard, thanks for sharing.

    . . . . .

  14. March 27, 2014 1:12 am

    If you are going for most excellent contents like myself, just pay
    a quick visit this web page all the time as it gives feature contents, thanks

  15. April 13, 2014 5:23 pm

    The data furthermore word of advice very within reach to me.
    Thanks dreadfully a lot before hand. Your current erudition about this theme is fantastic, I’m glad to facilitate suggestions retrieve.
    Many thanks another time!

  16. April 17, 2014 10:03 am

    Many vitamins and minerals have co-factors that help enhance their effectiveness.

    Scientific studies have proven that directly injecting or taking HGH ineffectual.
    So why is it then that the diplomatic missions in Star Trek Online suck so hard.

  17. April 17, 2014 3:02 pm

    Heya! I just wanted to ask if you ever have any issues with hackers?
    My last blog (wordpress) was hacked and I ended up losing
    months of hard work due to no backup. Do you have any methods
    to prevent hackers?

  18. April 19, 2014 7:53 am

    An outstanding share! I’ve just forwarded this onto a coworker who was doing a little research on this.
    And he in fact ordered me dinner due to the fact that I found it for him…
    lol. So let me reword this…. Thank YOU for
    the meal!! But yeah, thanx for spending the time to discuss this issue here on
    your web site.

  19. May 3, 2014 2:30 am

    Jе mme permets d’écrire un petit com simplement pour remercier
    le webmaster

  20. May 21, 2014 2:22 am

    2013 Christmas bank holiday: Do banks close
    early on Christmas Eve. These are kits made for children who can start
    to understand what baseball, golf and tennis is all about.
    Good news with wooden toys is they are completely eco-friendly and do not garner harmful
    chemicals in the form of paints or other chemicals found in synthetics and plastics.
    Some of them also aide in teachings letters, numbers,
    and colors. I am putting out a call to all my friends and family.

    Through learning games we can teach children important concepts and life skills.
    The goggles are powered by actual infra-red driven night vision technology allowing kids to see others even when others
    cant see them. Other Indoor activities like cooking pretend games and indoor picnic help your kids
    understand how their parents do the house chores by imitating them.

    From the building blocks playing process, children’s body functions such as hand-eye coordination ability and
    hand-feet coordination ability can be gradually established
    and developed. That means that the child is beginning
    to grow his first set of teeth in and he is anxious to give them a go, which means that anything that the child picks up goes straight into his mouth.
    Many parents are pleased to hear that Step 2 baby
    toys are made in USA. Rubber chews and bones are also fun and
    beneficial to your dog. It’s an assembly of laboratory implements to
    use, as you and your child work together in experiments about scents and fragrances.
    When buying baby toys is recommended that the
    toy should meet the child’s age (toys, this should indicate on the label) and that it meets all necessary safety requirements.

    NBA Legend Shaquille O’Neal has been doing great charitable work for a few years now with Toys R Us for the Marine Toys for Tots Foundation.

  21. May 31, 2014 12:08 pm

    Merveilleux poste : persiste dans cette voie

  22. June 7, 2014 7:19 am

    I do not write a ton of comments, but i did some searching and wound up here JQuery Global Scope | Status Not Quo.

    And I actually do have some questions for you if it’s allright.

    Could it be simply me or does it seem like some of the responses come across like coming from brain dead visitors?
    😛 And, if you are writing at additional social sites, I would like to keep up
    with everything new you have to post. Could you list of all of your social pages like your Facebook
    page, twitter feed, or linkedin profile?

  23. June 22, 2014 3:21 pm

    I don’t leave a ton of remarks, however i did some
    searching and wound up here JQuery Global Scope | Status Not Quo.
    And I do have a few questions for you if it’s allright.

    Could it be only me or does it look like some of the
    comments appear like they are written by brain dead people?
    😛 And, if you are writing on additional online sites, I would like to keep
    up with anything fresh you have to post. Would you list of all of your public sites like your linkedin profile, Facebook page or twitter feed?

  24. June 28, 2014 1:04 am

    Attractive component of content. I simply stumbled upon your web site
    and in accession capital to claim that I acquire actually enjoyed account your blog posts.
    Any way I’ll be subscribing on your feeds and even I success you
    get right of entry to persistently quickly.

  25. July 18, 2014 7:31 am

    Hi there would you mind letting me know which webhost you’re using?
    I’ve loaded your blog in 3 different internet browsers and I must say this blog loads
    a lot quicker then most. Can you suggest a good hosting provider at
    a fair price? Kudos, I appreciate it!

  26. July 19, 2014 3:37 pm

    Why viewers still make use of to read news papers when in this technological globe the whole
    thing is existing on web?

  27. July 19, 2014 4:53 pm

    Link exchange is nothing else however it is simply placing the other
    person’s blog link on your page at appropriate place and other person will also do similar in support of you.

  28. August 15, 2014 12:14 am

    A motivating discussion is worth comment. I think that you need to publish more about this issue, it may not be a taboo subject but usually people do not
    speak about such subjects. To the next! Many thanks!!

  29. August 17, 2014 7:22 pm

    Hello friends, its great paragraph regarding cultureand entirely
    defined, keep it up all the time.

  30. August 18, 2014 1:30 pm

    Nice replies in return of this issue with genuine arguments and describing all regarding that.

  31. August 19, 2014 12:07 am

    I like what you guys tend to be up too. This type of clever work
    and coverage! Keep up the good works guys I’ve included you guys to my personal blogroll.

  32. August 20, 2014 10:05 am

    Thanks for finally talking about >JQuery Global Scope | Status Not Quo <Liked it!

  33. August 21, 2014 3:28 pm

    Hi! Would you mind if I share your blog with my twitter group?
    There’s a lot of people that I think would really enjoy your content.
    Please let me know. Thanks

  34. September 2, 2014 2:14 am

    My brother recommended I might like this blog.
    He used to be totally right. This put up actually
    made my day. You can not consider just how much time I had spent for this info!

  35. September 8, 2014 7:57 am

    This gives you access to the music player and all music related applications, services
    and tools. Try something similar to, “We Hate to Work on Toilets. Therecordisdonevindicateofvalue, but highlighting and more elaborate advertisement can beaddedbypaying.

  36. September 19, 2014 1:25 pm

    I am genuinely thankful to the owner of this site who has
    shared this wonderful piece of writing at at this place.

  37. September 22, 2014 1:04 am

    Thanks for sharing your thoughts. I truly appreciate your efforts and I
    will be waiting for your further write ups thanks once again.

  38. September 22, 2014 10:27 am

    Hello to all, because I am in fact eager of reading
    this blog’s post to be updated on a regular basis. It consists of good data.

  39. September 24, 2014 10:48 am

    Attractive portion of content. I simply stumbled upon your website and in accession capital to
    assert that I get actually enjoyed account your weblog posts.
    Anyway I’ll be subscribing for your augment and even I achievement you get admission to persistently rapidly.

  40. September 30, 2014 6:00 pm

    Often, the item is printed with a motivational
    message that the company has been using in their advertising.

    Struggle no more, Canadian company Geekware have a wide range of irresistible gifts that geeks
    will give their PCs for, and what’s more, they’re all environmentally
    friendly. A customer over-heard the employees talking about the cuts, and got so offended that
    she decided to return everything she just purchased, and left the store.

  41. October 2, 2014 5:34 pm

    Ford did not invent the automobile, he simply invented a
    method to produce cars in mass volumes and make them available
    for virtually anyone wishing to purchase a horse-less carriage.
    The collaboration was successful beyond anyone’s imagination. The raised print became popular for
    most brides and grooms.

  42. October 2, 2014 10:32 pm

    A potato stuffed prantha is filing, nutritious and tasty.
    This is one of my all-time favorite dishes to cook and eat.
    Once pumpkin is cooked, puree it in a food processor and set aside (you can also use an immersion blender, one of my favorite tools).

  43. October 9, 2014 5:39 pm

    They are a very good way to promote business service.
    They only want your money and they want as much of it as they can possibly get.
    Efficiency: Many carriers provide multiple receive emails, so your fax messages are automatically delivered to whomever you intend.

  44. October 14, 2014 11:08 pm

    They are a very good way to promote business service.

    As the culture of internet slang grew, it took on new origins
    from pop culture or video games and television. Make certain that the payment gateway you are making use of, permits similar languages as the
    remaining of the web pages so that they can match well together.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: