Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
jQuery Bad Practices
Search
Filipe Costa
November 09, 2013
Programming
270
2
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
jQuery Bad Practices
Let's learn some bad jQuery practices to avoid them.
Filipe Costa
November 09, 2013
More Decks by Filipe Costa
See All by Filipe Costa
Lidando com Efeitos Colaterais com Redux Saga
filipebarcos
0
230
Pitch - Lidando com Efeitos Colaterais com Redux Saga
filipebarcos
0
400
Rust for Rubysts
filipebarcos
2
260
Limpando Seu Código JS Com O Padrão Pub/Sub
filipebarcos
0
200
Tu trabalha em casa?? Que moleza hein!
filipebarcos
0
130
Rediscovering OOP in Rails World
filipebarcos
0
100
Intro to Ruby
filipebarcos
1
140
Other Decks in Programming
See All in Programming
Spring Security 実践 ─ GraphQL APIで実務に役立つ 認証・認可 を学ぶ
wagyu
0
230
並列実装の現場、2ヶ月間実務でAIを使い倒したAIもPCも私も限界が近い
ming_ayami
0
130
例外の正しい扱い方 そのエラー try-catchして大丈夫?
jinwatanabe
0
230
Java × distroless で 軽量なコンテナイメージを / Java on Distroless
contour_gara
0
540
決定論的オーケストレーションの設計と実装 / Design and Implementation of Deterministic Orchestration
nrslib
3
1.3k
Claspは野良GASの夢をみるか
takter00
0
190
net-httpのHTTP/2対応について
naruse
0
480
キャリア迷子上等 ─ "ない道"は自分で作ればいい
16bitidol
3
2.1k
PHPで使える日時の表現と、その知り方 #frontend_phpcon_do
o0h
PRO
0
240
AIとASP.NET Coreで雑Webアプリを作った話
mayuki
0
600
Skillsは効率化、Agentsは"自分の拡張"——Builder時代のエージェント編成(CC Night 2026)
wemra
1
130
Technical Debt: Understanding it Rightly, Engaging it Rightly #LaravelLiveJP
shogogg
0
220
Featured
See All Featured
Why You Should Never Use an ORM
jnunemaker
PRO
61
9.9k
Exploring the relationship between traditional SERPs and Gen AI search
raygrieselhuber
PRO
2
4k
Impact Scores and Hybrid Strategies: The future of link building
tamaranovitovic
0
310
How to Grow Your eCommerce with AI & Automation
katarinadahlin
PRO
1
210
Skip the Path - Find Your Career Trail
mkilby
1
150
DBのスキルで生き残る技術 - AI時代におけるテーブル設計の勘所
soudai
PRO
65
55k
SEOcharity - Dark patterns in SEO and UX: How to avoid them and build a more ethical web
sarafernandez
0
200
Building Better People: How to give real-time feedback that sticks.
wjessup
370
20k
Efficient Content Optimization with Google Search Console & Apps Script
katarinadahlin
PRO
1
620
Facilitating Awesome Meetings
lara
57
7k
Future Trends and Review - Lecture 12 - Web Technologies (1019888BNR)
signer
PRO
0
3.6k
WCS-LA-2024
lcolladotor
0
630
Transcript
jQuery Bad Practices Filipe Costa
Filipe Costa 4UBDL#VJMEFST @filipebarcos BCPVUNF pMJQFCBSDPT
DISCLAIMER
Really?? jQuery?!
https://github.com/search?l=Ruby&q=jquery&ref=advsearch&type=Repositories https://github.com/search?l=Python&q=jquery&ref=advsearch&type=Repositories https://github.com/search?l=JavaScript&q=jquery&ref=advsearch&type=Repositories
People say sh** about jQuery
Obtrusive Hard to follow Hard to maintain Disorganized Bloated Slow
Difficult to talk about
;(function(window, document, $) {! var isInputSupported = 'placeholder' in document.createElement('input');!
var isTextareaSupported = 'placeholder' in document.createElement('textarea');! var prototype = $.fn;! var valHooks = $.valHooks;! var propHooks = $.propHooks;! var hooks;! var placeholder;! ! if (isInputSupported && isTextareaSupported) {! placeholder = prototype.placeholder = function() {! return this;! };! placeholder.input = placeholder.textarea = true;! } else {! ! placeholder = prototype.placeholder = function() {! var $this = this;! $this.filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')! .not('.placeholder')! .bind({! 'focus.placeholder': clearPlaceholder,! 'blur.placeholder': setPlaceholder! }).data('placeholder-enabled', true).trigger('blur.placeholder');! return $this;! };! placeholder.input = isInputSupported;! placeholder.textarea = isTextareaSupported;! hooks = {! 'get': function(element) {! var $element = $(element);! var $passwordInput = $element.data('placeholder-password');! if ($passwordInput) {! return $passwordInput[0].value;! }! return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;! },! 'set': function(element, value) {! var $element = $(element);! var $passwordInput = $element.data('placeholder-password');! if ($passwordInput) {! return $passwordInput[0].value = value;! }! if (!$element.data('placeholder-enabled')) {! return element.value = value;! }!
None
None
Caching
function whatever() {! $(".container input#elem").attr("title", $(".container input#elem").text());! $(".container input#elem").css("color", "red");!
$(".container input#elem").fadeOut();! }
This is BAD!
function whateverBetter() {! var elem = $("#elem");! elem.attr("title", elem.text());! elem.css("color",
"red");! elem.fadeOut();! }
We can do better than that
function whateverEvenBetter() {! var elem = $("#elem");! elem.attr("title", elem.text())! .css("color",
"red")! .fadeOut();! }
Querying DOM
Yo
$("div.data .user"); $(".data section.user");
Excessive Specificity
$(".data table.users td.user"); $(".data td.user");
Avoid Sizzle http://learn.jquery.com/performance/optimize-selectors/
$('#content p.title').fadeIn(); $('#content').find('p.title').fadeIn();
Avoid Universal Selectors
$(".countries :selected"); $(".countries input:selected");
Context
$('.selectbox-user').toggle(); $('.selectbox-user', '#user-table').toggle();
$(this) “jQuery way"
$('.input-field').on('focus', function()) {! console.log($(this).val());! } $('.input-field').on('focus', function()) {! console.log(this.value);! }
DRY
function whateverEvenBetter() {! var elem = $("#elem");! elem.attr("title", elem.text())! .css("color",
"red")! .fadeOut();! }
AJAX
function getCities(state) {! $.ajax({! url: '/cities',! type: 'get',! data: state,!
success: function(data) {! $('.user-form-states-select').html(data);! }! });! }
That’s just the beginning
//functions.js! function getCities(state) {! return $.ajax({! url: '/cities',! type: 'get',!
data: state! });! }! ! //user.js! var FillSelectBox = function(data) {! $('.user-form-state-select').html(data);! }! ! getCities('CE').then(FillSelectBox);
Optimisation
jQuery won’t take care of UR dumbness
var names = ["Greg", "Peter", "Kyle", "Danny", "Mark"];! $.each(names, function(index,
value) {! $("ul.people").append("<li id=" + index + ">" + value + "</li>");! });
Caching again?
var names = ["Greg", "Peter", "Kyle", "Danny", "Mark"],! list =
$("ul.people");! $.each(names, function(index, value) {! list.append("<li id=" + index + ">" + value + "</li>");! });
We can do better than that
var names = ["Greg", "Peter", "Kyle", "Danny", "Mark"],! ! list
= $("ul.people"),! ! listItems = "";! ! $.each(names, function(index, value) {! listItems += "<li id=" + index + ">" + value + "</li>";! });! ! list.append(dynamicItems);
Safety
NOPE
var j = jQuery.noConflict();
jQuery(document).ready(function($) { ! //your code here! });
But U R cool
So U ain’t use jQuery
jk
(function($) {! //your code here! })(jQuery);
</code>
I use jQuery and I’m still cool
jQuery is your FRIEND
Learn how to use it
jQuery is just a tool
USUALLY, it’s not tool's fault
Thank you! Filipe Costa @filipebarcos