Ditching jQuery Madison

31
Ditching JQuery Hao Luo Northwestern University https://joind.in/16012

Transcript of Ditching jQuery Madison

Ditching JQueryHao Luo Northwestern University

https://joind.in/16012

Ditching JQuery - Hao Luo - Madison PHP

Intro

2

4 years as a full-time web developer

@[email protected]

Ditching JQuery - Hao Luo - Madison PHP

I ❤ JQuery •One codebase, all the browser!• Introduced me to JavaScript• “It just works”

3

Ditching JQuery - Hao Luo - Madison PHP

Goal of This Talk•Not to convince anyone• Important to understand the basics•Lessen the hurdle to start using pure JavaScript

4

Ditching JQuery - Hao Luo - Madison PHP5

Scenario Problem

Ditching JQuery - Hao Luo - Madison PHP

Our Late Stay Requirements

Admin can…•See a list of applications with some information•Can decide to approve or deny an application•Can delete an application•Can add a random application

6

Ditching JQuery - Hao Luo - Madison PHP

IE9 Demo

7

github.com/howlowck/latestay-purejsgithub.com/howlowck/latestay-jquery

Ditching JQuery - Hao Luo - Madison PHP

Late Stay Workflow

8

HTTP GET latestayapp.com/purejs

HTML (empty ul#applications container)

AJAX GET latestayapp.com/applications

JSON (parses then inserts in #applications container)

(admin clicks on the approve button)

AJAX PUT latestayapp.com/applications/20/approve

JSON (update HTML)

AJAX

DOM

Events

Ditching JQuery - Hao Luo - Madison PHP

DOMQuerying, Traversal, and Manipulation

9

Ditching JQuery - Hao Luo - Madison PHP

Some DOM Operations

10

JQuery Vanilla JS$(‘#application-20’); document.querySelector(‘#application-20’);

$el.attr(‘data-id’,‘20’);$el.attr(‘data-id’);

el.setAttribute(‘data-id’,‘20’);el.getAttribute(‘data-id’);

yes yes yes 9+

yes yes yes yes

yes yes yes 10+$el.addClass(‘approved’);$el.removeClass(‘approved’);$el.toggleClass(‘approved’);

el.classList.add(‘approved’);el.classList.remove(‘approved’);el.classList.toggle(‘approved’);

$el.data(‘id’,‘20’);varid=$el.data(‘id’);

el.dataset.id=‘20’;varid=el.dataset.id; yes yes yes 11+

$button.closest(‘.application’); button.closest(‘.application’); 41 35 no no

https://dom.spec.whatwg.org/#dom-element-closestselectors

https://github.com/eligrey/classList.js/

Ditching JQuery - Hao Luo - Madison PHP

Polyfills

11

A polyfill is a piece of code that provides the technology that the developer expects the browser to provide natively. Flattening the API landscape if you will. - Remy Sharp

varELEMENT=Element.prototype;

ELEMENT.matches=ELEMENT.matches||ELEMENT.msMatchesSelector||ELEMENT.mozMatchesSelector||ELEMENT.webkitMatchesSelector;

ELEMENT.closest=ELEMENT.closest||function(selector){varnode=this;while(node){if(node.matches(selector)){break;}node=node.parentElement;}returnnode;};

41 35 no no

yes yes yes 9+

<liclass="application"id=“#application-20">…

<divclass="action-bar"><divclass=“action">

…<buttonclass="delete"></div></div></li>

deleteButton.closest('.application');

HTML

Javascript

Javascript

Ditching JQuery - Hao Luo - Madison PHP

DOM Events

12

Ditching JQuery - Hao Luo - Madison PHP13

Register Event CallbacksYes Yes Yes 9+

JQuery $('.delete').on('click',deleteApplication);

Vanilla JSgetAllElToArr('.delete').forEach(function(el){el.addEventListener('click',deleteApplication);});

Ditching JQuery - Hao Luo - Madison PHP

li.application ☺☹ ✖li.application ☺☹ ✖

Direct Events (vs Delegated Events)

14

li.application

li.application

li.application

div#application-container

ul#applications

li.application

JQuery $('.delete').on('click',deleteApplication);

Vanilla JSgetAllElToArr('.delete').forEach(function(el){el.addEventListener('click',deleteApplication);});

EventListener #1

EventListener #4

EventListener #3

EventListener #2

EventListener #5

EventListener #6

Ditching JQuery - Hao Luo - Madison PHP

li.application ☺☹ ✖

Delegated Events

15

li.application

li.application

li.application

div#application-container

ul#applications

li.application

li.application ☺☹ ✖

JQuery $(‘ul.applications’).on(‘click’,‘.deleteBtn’,deleteApplication);

Vanilla JS NoStandardforEventDelegation:(✖

EventListener #1

is the ‘click’ target element the ‘.delete’ button? if so, run deleteApplication

is the ‘click’ target element the ‘.approve’ button? if so, run approveApplication

https://github.com/ftlabs/ftdomdelegate

Ditching JQuery - Hao Luo - Madison PHP

AJAX

16

Ditching JQuery - Hao Luo - Madison PHP

AJAX

17

JQuery $.ajax();

Vanilla JS XMLHttpRequest

HTML5 FetchAPI

yes yes yes yes

41 no no no

Fetch API Polyfill: https://github.com/github/fetch

yes yes yes 9+

Ditching JQuery - Hao Luo - Madison PHP

POST - A Closer Look

18

JQuery XMLHttpRequest

$.ajax('/applications',{method:'POST',contentType:'application/json',processData:false,data:JSON.stringify({name:'JoeBob',reason:'Toocoldoutside'})}).then(functionsuccess(application){appendApplicationHTML(application);}).fail(functionfailed(){console.log('requestfailed!');});

xhr=newXMLHttpRequest();xhr.open('POST','/applications'));xhr.setRequestHeader('Content-Type','application/json');xhr.onload=function(){if(xhr.status===200){varapplicationInfo=JSON.parse(xhr.responseText);appendApplicationHTML(application);}

elseif(xhr.status!==200){alert('Requestfailed.');}};xhr.send(JSON.stringify({name:'JoeBob',reason:'Toocoldoutside'});

Ditching JQuery - Hao Luo - Madison PHP

POST - A Closer Look

19

JQuery Fetch API

$.ajax('/applications',{method:'POST',contentType:'application/json',processData:false,data:JSON.stringify({name:'JoeBob',reason:'Toocoldoutside'})}).then(functionsuccess(application){appendApplicationHTML(application);}).fail(functionfailed(){console.log('requestfailed!');});

fetch('/users',{method:'post',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:'JoeBob',reason:'TooColdOutside'})}).then(function(response){returnresponse.json();}).then(function(application){appendApplicationHTML(application);}).catch(function(error){console.log('requestfailed',error);});

Ditching JQuery - Hao Luo - Madison PHP

Deferred Value Eliminates Callback hell Offers More Flexibility and Freedom

Promises are awesome

20

Ditching JQuery - Hao Luo - Madison PHP

Utilities

21

Ditching JQuery - Hao Luo - Madison PHP

DOM Loaded

22

JQuery Vanilla JS$(function(event){console.log("DOMfullyloadedandparsed");});

document.addEventListener("DOMContentLoaded",function(event){console.log("DOMfullyloadedandparsed");});

yes yes yes 9+

Don’t use "load"

Ditching JQuery - Hao Luo - Madison PHP

HTML Parse

23

JQuery Vanilla JS

varel=$.parseHTML(HTMLString);varparser=newDOMParser();vardoc=parser.parseFromString(HTMLString,'text/html');varel=doc.body.firstChild;

30 12 7.1 10+

functionparseHTML(str){vartmp=document.implementation.createHTMLDocument('');tmp.body.innerHTML=str;returntmp.body.firstChild;};

IE9 won’t accept empty paramyes yes yes 9+

Ditching JQuery - Hao Luo - Madison PHP

Date Parse IE9 needs W3C output (which is also ISO 8601 compliant) (http://www.w3.org/TR/NOTE-datetime-970915.html)

24

<?php$objDateTime=newDateTime('NOW');echo$objDateTime->format('c');//1975-12-25T14:15:16-05:00YesIE9echo$objDateTime->format(DateTime::ISO8601);//1975-12-25T14:15:16-0500NoIE9

Ditching JQuery - Hao Luo - Madison PHP

A word about JQuery Animate

•Use Semantic HTML•Use CSS Transition

25

.application{opacity:1;max-height:300px;transition:max-height0.5s,opacity0.7s;}

.application.removed{max-height:0;opacity:0;}

CSS

Ditching JQuery - Hao Luo - Madison PHP

Closing Thoughts

26

Ditching JQuery - Hao Luo - Madison PHP27

Non-Technical Reasons

• a lot of magic is confusing sometimes

• Understanding the basics makes you a better developer

$('div');//createsajqueryinstancewiththeselectioninside$('<div>');//createsajqueryinstancewithanewelementnotindocument$($aJQueryInstance);//makesacloneof$aJQueryInstance$(function(){})//registersfunctiontorunafterDOMisloaded$({foo:'bar'});//???createsajquerysetthathasasubsetofmethods???

var$appsEl1=$('#applications');var$appsEl2=$('#applications');$appsEl1===$appsEl2;//false

varappsEl1=document.querySelector('#applications');varappsEl2=document.querySelector('#applications');appsEl1===appsEl2;//true

Ditching JQuery - Hao Luo - Madison PHP

Some Takeaways•Avoid monolithic libraries & frameworks and Use Packages and Polyfills

•Out of the JQuery Plugin Ecosystem and into NPM or Bower

•Browser and Server

28

Ditching JQuery - Hao Luo - Madison PHP

When to use JQuery•When you have to support IE8•When you don’t have CORS•Abstractions sometimes are good!

29

uses requestAnimationFramesforitsanimationsuses setIntervalforitsanimations

Ditching JQuery - Hao Luo - Madison PHP

Resources for DOM references

http://blog.garstasio.com/you-dont-need-jquery/ http://youmightnotneedjquery.com/ http://html5please.com/

30

Ditching JQuery - Hao Luo - Madison PHP

Thank you!

@howlowck

https://joind.in/16012

31