Reblog: Optimize jQuery selectors

I have always found jQuery selectors very complex and have never quite understood how to use them properly.   I just found this article from the website Optimize your jQuery selectors for best performance.  It is a fantastic article and full credit goes to them.  The only reason I am copying it here is because I want to make sure that the information stays in my toolbox.   Please check out their page to see more information.


• ID selector $(‘#elementID’)
• Tag selector $(‘p’)
• Class selector $(‘.CSSClass’)
• Attribute selector $(‘[type=”text”]‘)
• Pseudo selector $(‘:visible’)

Always use ID selector if possible

Accessing DOM is a very expensive operation, so it’s beneficial to minimize effort and time. As we all know, the ID attribute is unique for each HTML element on the page. in JavaScript document.getElementById() is the function that one would use to select the HTML element. It’s the fastest and the best way to select the element because it directly maps to the element. jQuery is a library written on top of JavaScript, which means that it internally calls the JavaScript functions to do the job. When you use ID as a selector in jQuery, it internally calls document.getElementById(). To select the HTML element with elm as ID, the jQuery code looks like this: $(“#elm”);
This method works well in all browsers, so it’s a good choice if you are using an older browser.

Cache your selector

Caching improves the performance of the application. You can cache data or objects for better performance. You can also cache your jQuery selectors for better performance using the ID as your selector (as mentioned in the previous tip). When you don’t cache the selector, jQuery must rescan the DOM to get the element. You may not feel the difference in small applications, but with large applications this becomes very critical. Let’s look at the process of caching objects in jQuery. The following simple line of code caches the selector and stores it in the $elm variable:

var $elm = $("#elm");

Now use the $elm variable instead of using the jQuery ID selector. Like this:

var $elm = $("#elm");
 $elm.addClass(‘dummy’);

Remember, the scope of a variable is limited to where it is defined. If it is defined as a global variable then you can use it anywhere in the jQuery code, but if it is inside a method the scope will be limited to that particular method only. Global caching is useful for elements which are frequently used in the code.

Define a context with jQuery selectors

By default, jQuery selectors perform their search within the DOM. But while defining the selector, you can pass the context, which limits the searching range for the jQuery selector. In other words, you are instructing jQuery to look inot the context rather than beginning the search from the document root. This helps in speeding up the searching process which will definitely improve the performance. Passing the context is optional, but you should use it whenever you can.
Enough theory! Let’s take a look at a practical example. Consider the following HTML code:

<div id="”parent1”">
<div class="”child”"></div>
<div class="”child”"></div>
<div class="”child”"></div>
</div>

If you want to select all the div element with child class you can use the following jQuery code:

var $elm = $(".child");

The above code will search for elements with child class starting from the document root. It can be optimized by passing via an alternate selector. Like,

var $parent = $("#parent1");
 var $elm = $(".child", $parent);

This limits the search range, so now searching is limited to the div with ID parent1. The context argument can be a DOM element, a document, or a jQuery object. If you pass context, then jQuery will internally use the find method to retrieve the elements. So the above code is internally converted to:

var $elm = $parent.find(".child");

jQuery first checks if the passed context is a jQuery object. If it is, it calls the find() method on the given context. If the given context is a DOM element, it first converts it to a jQuery object and then executes the find() method. As such, it is better to pass the object as context instead of the DOM element because it will reduce the conversion time.

Don’t repeat your selectors

As mentioned earlier, you can cache the jQuery selectors which prevents you from repeating your selector. jQuery also offers chaining, which allows you to chain multiple methods in a single call. Consider the following jQuery code:

$("div").css("color", "red");
 $("div").css("font-size", "14px");
 $("div").text("New Text!");

Below is the first optimized version using caching:

var $div = $("div");
 $div.css("color", "red");
 $div.css("font-size", "14px");
 $div.text("New text goes here!");

Next is the second optimized version using chaining:

$(“div”).css({“color”, “red”, “font-size”, “14px”}).text(“New text goes here!”);

Use class selector wisely

jQuery also provides a CSS class selector which allows you to select elements with a particular CSS class. This is again a very useful and popular selector as it allows you to select multiple elements at once. However, you have to be cautious while using class selector. The following jQuery code will select all the elements with “dummy” class applied to them:
$(“.dummy”)

In this case, jQuery has to scan the complete DOM to discover elements with dummy class. As mentioned earlier, traversing DOM is a very expensive process so it’s always better to minimize this effort. In this case, you can pass a tag name to reduce the searching scope. Like this:

$("div.dummy");

The above code tells jQuery to only give me the DIV elements with dummy CSS class applied. Though the class selector works quite well in modern browsers, older browsers have performance issues with class selector. That being said, it’s not always a good choice to add a tag name with class selector. Why?

In this example, jQuery will first search for all elements with class dummy and then filter records to only return those elements that are div elements. So when the dummy class is only meant for div elements, you need to specify the tag name in order to add an extra step of filtering. Keep in mind that this is only useful when the CSS class is applied to different HTML elements like span, paragraph and div.

Be very specific about selectors

Did you know that jQuery selectors are executed from right to left? In other words, the last selector will be executed first when there are multiple selectors. Consider the following example:

$("div.parent .child");

In this example, jQuery will first search for all elements with class child (last selector executed first) and then apply a filter to return only those elements which are div elements with a parent class applied. This is the optimized version:

$(".parent div.child");

Here we are more specific on the last selector, which helps to speed up performance!

Look for an alternative for the Pseudo selector

Pseudo class selectors are CSS selectors with a colon preceding them. They are also available with jQuery – :visible, :checked or :first. Pseudo selectors are useful for selecting elements with different states, or a particular element from a set of elements, but they are slower compared to other jQuery selectors. You should either find a way to replace the pseudo selector or be very specific in using it. Let’s take a look at examples of both. The following jQuery code selects all elements which are visible:

$(":visible");

You can be more specific here. Like,

$("input:visible");

or even better,

$("form").find("input:visible");

Pseudo selectors like :first, :last and :eq allow you to select a particular element from a set of elements. As an example, the following jQuery code will select the first table row using the :first pseudo selector.

$("tr:first")

The above code can be replaced with better performing code, but first you need to cache the selector (table row in this case).

var tRows=$('tr');

Since jQuery stores this as an array, we can take advantage of it. To get the first table row:

var firstRow=$(tRows[0]);

To get the last element (:last),

var lastRow = $(tRows[tRows.length - 1]);

Or to get any nth row (:eq(n)),

var nRow=$(tRows[n]);

 

Paging Example

This is a great example of doing paging in SQL versus on the front end.

-- find activity logs
insert into @tblActivityLogs
select al.ActivityLogId
	, al.TargetPartyId
	, pWhoDidIt.PartyId
from dbo.ActivityLog al
left join dbo.Party pWhoDidIt on al.PartyIdentifier = pWhoDidIt.Identifier
where al.TargetPartyID = @PartyId
	and al.Created >= @DateTimeRangeFrom
	and al.Created <= @DateTimeRangeTo
order by al.Created
	offset ((@Page - 1) * @PageSize) rows fetch next @PageSize rows only

SQL Saturday #682

Full Session Schedule

https://www.youtube.com/user/SQLPASSTV

Session #1: Reading Execution Plans Successfully

By: Arthur Daniels

Twitter: https://twitter.com/arthurdanSQL?lang=en

http://www.dba-art.com/

If you’ve seen an execution plan but didn’t know how to read it, this session is for you.

The goal of this session to learn how SQL Server is interpreting your query into an execution plan. We’ll discuss execution plan internals, how SQL Server estimates the cost of your query, and what a graphical execution plan is displaying through its operators.

Learning to read an execution plan is a great way to begin troubleshooting performance. At the end, we will take a look at how SQL Server 2016 provides more tools for exploring execution plans.

Notes:

Session #2: Getting Started with Extended Events 

By: Andy Galbraith

Twitter: https://twitter.com/DBA_ANDY?lang=en

http://nebraskasql.blogspot.com/

Few subjects in Microsoft SQL Server inspire the same amount of Fear, Uncertainty, and Doubt (FUD) as Extended Events. Many DBA’s continue to use Profiler and SQL Trace even though they have been deprecated for years. Why is this?

Extended Events started out in SQL Server 2008 with no user interface and only a few voices in the community documenting the features as they found them. Since then it has blossomed into a full feature of SQL Server and an amazingly low-impact replacement for Profiler and Trace.

Come learn how to get started – the basics of sessions, events, actions, targets, packages, and more. We will look at some base scenarios where Extended Events can be very useful as well as considering a few gotchas along the way. You may never go back to Profiler again!

Notes:

Session #2: Query Optimization Statistics : Driving Force Behind Performance

By: Vern Rabe

Twitter: https://twitter.com/VernRabe?lang=en

http://rabedata.com/

When the SQL Server optimizer evaluates a query to determine how best to execute it, the statistics are quite possibly the most important tool at its disposal. But SQL Server statistics objects aren’t perfect because they only contain estimated summary information. In this session, we’ll start with an overview of what the statistics objects are, how the optimizer uses them, and some general guidelines for their maintenance. Then we’ll look at some of the issues, how to find them, and how to solve them, that can arise due to their imperfection: ascending keys (the most prevalent statistics based performance killer?), correlated predicates, skewed distribution, or downright bad summary information. There’ll be many examples, and even a stored procedure to help you find ascending keys. By applying the techniques we’ll discuss, you WILL see improved query performance.

    

Notes:

Session #2: Getting the most out of SQL Server Data Tools 

By: Eric Strom

Twitter:

SSDT has been around for a while, but a lot of people don’t use the tool to its full capabilities.  In this session, we will cover writing unit tests, good deployment script writing practices, T4 and command variables.  This session requires a good understanding of T-SQL and Visual Studios.

Session #3: Lightning Talks (Round 1)

Vagrant Auto Build System

By: Mitchell Hamann

This session talked about the Vagrant Software that can be used to build SQL development VMs and deploy to developers machines.

The bonus to doing something  like this is that the SQL tools may not need to be installed on each developers machine.

SQL Server Monitoring on No Budget

By: Daniel Crowson

A review of different free software that can be used to monitor your SQL server including sp_whoisactive, DMVs, Perfmon Counters.

In the Q&A session the following list of lower budget options were also listed:

  • SQL Monitor
  • FogLight
  • Brent Ozar (Highly recommended)
  • Solar Winds
  • Sentry One (Highly recommended)
  • SP Blitz
  • Stack Overflow Observor

Testing Backups in One step

By: Constantine (CK) Kokkinos

Twitter: https://twitter.com/mobileck

https://constantinekokkinos.com/

Session about using the https://dbatools.io/ software to test the current state of databases quickly and cleanly.

Session #3:  Index 360 – Looking at Indexes from Multiple Perspectives

By: John Eisbrener

Twitter: https://twitter.com/johnedba?lang=en

http://www.dbatlas.com

If you have used a database, chances are almost certain you’ve utilized indexes as well.  In this presentation I will discuss both Rowstore and Columnstore Indexes and why they are important to anyone that interacts with a database.  This session will cover what they are, how they are utilized, how best to take advantage of them, and even when they can be problematic. It is my intention to help anyone become more comfortable with indexes and understand what they can do for you and your role, be it a DBA, Developer, or BI Professional.

Session #4: Difficult Queries

By: Rick Bielawski

https://rickbielawski.wordpress.com/

Notes:

  • Cross Joins, Cursors
  • Snooze

Session #5: Intro to Machine Learning

By: Jared Zagelbaum

Notes:

 

  • Flew wayyyyy over my head.

Session #5: Free SQL Server Tools

By: Cecil Spivey

Everybody loves a free lunch. Come to this session to learn about all the SQL Server freebees.

The Programmers Oath by Uncle Bob

The Programmers Oath by Uncle Bob

In order to defend and preserve the honor of the profession of computer programmers,

I Promise that, to the best of my ability and judgement:

  1. I will not produce harmful code.
  2. The code that I produce will always be my best work. I will not knowingly allow code that is defective either in behavior or structure to accumulate.
  3. I will produce, with each release, a quick, sure, and repeatable proof that every element of the code works as it should.
  4. I will make frequent, small, releases so that I do not impede the progress of others.
  5. I will fearlessly and relentlessly improve my creations at every opportunity. I will never degrade them.
  6. I will do all that I can to keep the productivity of myself, and others, as high as possible. I will do nothing that decreases that productivity.
  7. I will continuously ensure that others can cover for me, and that I can cover for them.
  8. I will produce estimates that are honest both in magnitude and precision. I will not make promises without certainty.
  9. I will never stop learning and improving my craft.

SQL: Comma Delimited List

I’ve never seen this way of creating a comma delimited list in SQL before and don’t want to loose the logic.

SELECT STUFF
(
    (
        SELECT  ',' + aat.AccessTokenCode
        FROM AssetAccessToken aat
        WHERE aat.AssetID = a.AssetID
        GROUP BY aat.AccessTokenCode
        FOR XML PATH ('')
    ), 1, 1, ''
) as 'AssetAccessTokens'

Twin Cities Code Camp #21

Over the weekend our team got together and all attended the Twin Cities Code Camp together.  It was a ton of fun and I have lots of new tech stuff to research.  Here is a summary of my notes.

Unboxing ASP.NET Core

by Kevin Leung
  @KSLHacks 

http://kevinleung.com/

“ASP.NET Core is a new open-source Web framework optimized for building cross-platform web apps, IoT apps and mobile backends. ASP.NET Core comes with great new features ready to use out of the box with minimal setup required! In this talk we’ll look at .NET Core, architecture, package management and how to begin weighing the options between choosing .NET Framework and .NET Core. I will also share my experiences and insights while working alongside the .NET Core team at Microsoft to port over an existing project from .NET Framework to .NET Core; as well as the challenges we faced. Core brings Microsoft into the exciting world of open-source, cross-platform and package modularity/portability – Let’s see what we can build!”

Notes:

 

Building Reusable UI Components in ASP.NET Core MVC

by Scott Addie
  @Scott_Addie 

https://scottaddie.com/

“ASP.NET proper MVC developers have long relied upon partial views and HTML helpers to construct reusable UI components. ASP.NET Core MVC expands the arsenal of options for creating such UI components by introducing view components and tag helpers. Do these new offerings render partial views and HTML helpers obsolete? Absolutely not! Using the right tool for the job is important, which means understanding the differences between these options is paramount. In this session, you’ll gain an understanding of when it’s most appropriate to use each of them in the real world. You’ll also see how to create basic view components and tag helpers.”

Notes

 

Building Shiny Web Apps with TypeScript and Angular 2

by Dustin Ewers
  @dustinjewers 

https://dustinewers.com/

“From humble beginnings, JavaScript has gone from a hastily thrown together language for web pages to a hastily thrown together language that runs everywhere. If you can do it with code, you can probably do it in JavaScript. It’s the Swiss Army Knife of programming languages.  Unfortunately, JavaScript wasn’t designed for the large scale apps we use it in today. We’ve had to rely on design patterns, willpower, and luck to mitigate JavaScript’s failings. However, there is a better way. TypeScript adds features to JavaScript that make it usable on large projects. Additionally, the bar for web applications gets higher everyday. jQuery was cool ten years ago, but it doesn’t cut it for modern web apps. We need something with a little more horsepower. Angular 2 makes it easy to build clean, modular web apps. In this talk, we’ll explore TypeScript and Angular 2 and how they can be used together to build large-scale web applications. We will learn how to get started and get up to speed quickly.”

Notes

Unit Testing for the Scared, Skeptical and Ashamed

by J Wynia
  @jwynia 

http://www.wynia.org/

“Does the mention of the phrase “unit testing” make your “fight or flight” response kick in? Do you feel like the right time to get started unit testing was a while back and you missed the boat? Do you just have a hard time believing that writing unit tests won’t cut your development speed in half? Come learn about getting started unit testing in a judgement-free environment. Examples in C#, but applicable to other languages as well.”

Notes

 

Cool SQL Server Features Everyone Should Know About

by David Berry
  @DavidCBerry13 

http://buildingbettersoftware.blogspot.com/

“We all use SQL Server every day in our jobs, so it pays to know what SQL Server can do for us that will make our jobs easier. This talk will introduce you to some key features of SQL Server that you might not know about but will definitely want to use once you learn about them. First, we’ll discuss temporal tables, which provide a convenient way to track all of the changes made to data in a table. Second, we’ll talk about the JSON support built into SQL Server 2016 and what capabilities it provides us. Third, we’ll cover some advanced SQL constructs like the MERGE statement and Common Table Expressions that can make the SQL you write simpler. And finally, we’ll wrap up by talking about the windowing functions in SQL Server, which provide powerful analytic capabilities to our SQL Statements. After this talk, you will better appreciate some of the rich functionality built into SQL Server and understand how to use these capabilities to make your job easier.”

Notes