SlideShare a Scribd company logo
DOM and Browser Patterns
Carl
2016/02/23
1
Outline
Separation of Concerns
DOM Scripting
Events
Long-Running Scripts
Remote Scripting
Deploying JavaScript
Loading Strategies
Summary
2
Separation of Concerns
Content
HTML
Presentation
CSS
Behavior
JavaScript
3
Separation of Concerns
Test without CSS/JS
No inline event handlers or style(?)
ReactJS JSX: <button onClick={this.test(this)}>Submit</button>
Semantically HTML elements
4
Capability Detection
Check function exist instead of check browser agent
// antipattern
if (navigator.userAgent.indexOf('MSIE') !== −1) {
document.attachEvent('onclick', console.log);
}
// better
if (document.attachEvent) {
document.attachEvent('onclick', console.log);
}
// or even more specific
if (typeof document.attachEvent !== "undefined") {
document.attachEvent('onclick', console.log);
} 5
DOM Scriping
DOM Access
DOM Manipulation
6
DOM Access
Avoiding DOM access in loops
Assigning DOM references to local variables and working with the locals
Using selectors API where available
Caching the length when iterating over HTML collections (see Chapter 2)
7
Avoiding DOM access in loops
// antipattern
for (var i = 0; i < 100; i += 1) {
document.getElementById("result").innerHTML += i + ", ";
}
// better - update a local variable
var i, content = "";
for (i = 0; i < 100; i += 1) {
content += i + ",";
}
document.getElementById("result").innerHTML += content;
8
Assigning DOM references to local variables and working with the locals
// antipattern
var padding = document.getElementById("result").style.padding,
margin = document.getElementById("result").style.margin;
// better
var style = document.getElementById("result").style,
padding = style.padding,
margin = style.margin;
9
Using selectors API where available
document.querySelector("ul .selected");
document.querySelectorAll("#widget .class");
https://developer.mozilla.org/zh-TW/docs/Web/API/document.querySelector
Faster than jQuery Dom method
document.getElementById(myid) is still the fatest
https://jsperf.com/getelementbyid-vs-queryselector/25
10
DOM Manipulation(Document Fragment)
// antipattern
// appending nodes as they are created
var p, t;
p = document.createElement('p');
document.body.appendChild(p);
p = document.createElement('p');
document.body.appendChild(p);
11
DOM Manipulation(Document Fragment)
var p, t, frag;
frag = document.createDocumentFragment();
p = document.createElement('p');
frag.appendChild(p);
p = document.createElement('p');
frag.appendChild(p);
document.body.appendChild(frag);
https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment
12
DOM Manipulation(Document Fragment)
var oldnode = document.getElementById('result'),
clone = oldnode.cloneNode(true);
// cloneNode(true) if the children of the node should also be cloned, or false to clone
only the specified node.
https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
// work with the clone...
// when you're done:
oldnode.parentNode.replaceChild(clone, oldnode);
13
Events
Events Handling
Event Delegation
14
Events Handling
Use addEventListener/attachEvent instead of onxxx(ex: onclick)
onxxx bind to only one event
15
Event Delegation
Bind event to parent instead of child
Use event.target to check the target node
Pros
reduce event listeners
Cons
hard to find the event listener from browser developer tool
Demo
http://codepen.io/anon/pen/vLqvaV 16
Event Delegation
ReactJS JSX: <button onClick={this.test(this)}>Submit</button>
React use single top level event listener
https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#under-the-hood-
autobinding-and-event-delegation
17
Long-Running Scripts (setTimeout)
var timer1 = setTimeout(myfunction1, 50);
var timer2 = setTimeout(myfunction2, 100);
var timer3 = setTimeout(myfunction3, 150);
18
Long-Running Scripts (Web Wrokers)
var ww = new Worker('my_web_worker.js');
ww.onmessage = function (event) {
document.body.innerHTML += "<p>message
from the background thread: " + event.data + "</p>";
};
// Output
message from the background thread: hello there
message from the background thread: halfway there,
`tmp` is now 3749999975000001
message from the background thread: all done
19
// my_web_worker.js
var end = 1e8, tmp = 1;
postMessage('hello there');
while (end) {
end -= 1;
tmp += end;
if (end === 5e7) { // 5e7 is the half of 1e8
postMessage('halfway there, `tmp` is now '
+ tmp);
}
}
postMessage('all done');
Remote Scripting
XMLHttpRequest
JSONP
Frames and Image Beacons
20
XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) { // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState
return false;
}
if (xhr.status !== 200) {
alert("Error, status code: " + xhr.status);
return false;
}
document.body.innerHTML += "<pre>" + xhr.responseText + "</pre>";
};
xhr.open("GET", "page.html", true);
xhr.send("");
21
JSONP
Not restricted by the same-domain policy (Use script tag)
Often JSON wrapped in a function call
https://zh.wikipedia.org/wiki/JSONP
var script = document.createElement("script");
script.src = “http://remote.org/getdata.php?callback=myHandler”;
document.body.appendChild(script);
// Output of http://example.org/getdata.php?callback=myHandler
myHandler({“hello”: “world”});
22

More Related Content

DOCX
As props
PDF
Configurações distribuídas com Spring Cloud Config
PDF
淺談 Groovy 與 AWS 雲端應用開發整合
KEY
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
PDF
Creating ASTTs The painful truth
PDF
Service worker - Offline Web
PDF
InheritedWidget is your friend - GDG London (2018-08-08)
PPT
Real world cross-platform testing
As props
Configurações distribuídas com Spring Cloud Config
淺談 Groovy 與 AWS 雲端應用開發整合
Groovy Ecosystem - JFokus 2011 - Guillaume Laforge
Creating ASTTs The painful truth
Service worker - Offline Web
InheritedWidget is your friend - GDG London (2018-08-08)
Real world cross-platform testing

Viewers also liked (18)

PDF
Understanding Coroutine
PDF
Weird delivered things
PPTX
COMO SUBIR UN ARCHIVO PPT A SLIDESHARE
PDF
Gwelsh Proto June 2015
PDF
Intuitive understanding of backend dev
PPT
Annotated learning-sequence
PPTX
Ubicar el lugar adecuado, uso de mobiliario y equipo de acuerdo a las polític...
PPTX
Consideraciones para instalar un equipo de cómputo
PDF
월말보고서 견본
PPT
Puertos y conectores del pc
DOCX
Proyecto. Trabajos del Primer Parcial de Informática III
PDF
KhuHub student guideline
PDF
ブロックチェーン技術とそのビジネス応用への可能性 14 dec2015 のコピー
ODP
Les tres lletres
ODP
El món de l'armari
PDF
OSC北海道 2016 REST API を活用した、新しい WordPress サイト製作手法
PDF
Investors presentation for ChefCuisine
Understanding Coroutine
Weird delivered things
COMO SUBIR UN ARCHIVO PPT A SLIDESHARE
Gwelsh Proto June 2015
Intuitive understanding of backend dev
Annotated learning-sequence
Ubicar el lugar adecuado, uso de mobiliario y equipo de acuerdo a las polític...
Consideraciones para instalar un equipo de cómputo
월말보고서 견본
Puertos y conectores del pc
Proyecto. Trabajos del Primer Parcial de Informática III
KhuHub student guideline
ブロックチェーン技術とそのビジネス応用への可能性 14 dec2015 のコピー
Les tres lletres
El món de l'armari
OSC北海道 2016 REST API を活用した、新しい WordPress サイト製作手法
Investors presentation for ChefCuisine
Ad

Similar to JavaScript patterns chapter 8 of mine (20)

PDF
Introduction to jQuery
PDF
Javascript Browser Events.pdf
PPT
The Theory Of The Dom
ODP
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
ODP
Building serverless application on the Apache Openwhisk platform
PPTX
Windows Store app using XAML and C#: Enterprise Product Development
PPT
JavaScript Basics
PDF
Integration tests: use the containers, Luke!
ODP
Android Nâng cao-Bài 9-Debug in Android Application Development
PDF
Meetup Performance
PDF
Meetup Performance
PDF
Js Saturday 2013 your jQuery could perform better
PPTX
Modern Web Technologies
PPTX
jQuery Best Practice
DOCX
Selenium Testing Training in Bangalore
PPTX
Andrii Dembitskyi "Events in our applications Event bus and distributed systems"
PPTX
Building high performance web apps.
PDF
20150812 4시간만에 따라해보는 windows 10 앱 개발
PDF
lecture5
PDF
lecture5
Introduction to jQuery
Javascript Browser Events.pdf
The Theory Of The Dom
Lucio Grenzi - Building serverless applications on the Apache OpenWhisk platf...
Building serverless application on the Apache Openwhisk platform
Windows Store app using XAML and C#: Enterprise Product Development
JavaScript Basics
Integration tests: use the containers, Luke!
Android Nâng cao-Bài 9-Debug in Android Application Development
Meetup Performance
Meetup Performance
Js Saturday 2013 your jQuery could perform better
Modern Web Technologies
jQuery Best Practice
Selenium Testing Training in Bangalore
Andrii Dembitskyi "Events in our applications Event bus and distributed systems"
Building high performance web apps.
20150812 4시간만에 따라해보는 windows 10 앱 개발
lecture5
lecture5
Ad

Recently uploaded (20)

PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
medical staffing services at VALiNTRY
PDF
top salesforce developer skills in 2025.pdf
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Transform Your Business with a Software ERP System
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Nekopoi APK 2025 free lastest update
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PPTX
Introduction to Artificial Intelligence
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
ai tools demonstartion for schools and inter college
PPTX
Operating system designcfffgfgggggggvggggggggg
Navsoft: AI-Powered Business Solutions & Custom Software Development
Which alternative to Crystal Reports is best for small or large businesses.pdf
medical staffing services at VALiNTRY
top salesforce developer skills in 2025.pdf
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Understanding Forklifts - TECH EHS Solution
Transform Your Business with a Software ERP System
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Reimagine Home Health with the Power of Agentic AI​
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Nekopoi APK 2025 free lastest update
PTS Company Brochure 2025 (1).pdf.......
VVF-Customer-Presentation2025-Ver1.9.pptx
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
2025 Textile ERP Trends: SAP, Odoo & Oracle
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Introduction to Artificial Intelligence
Design an Analysis of Algorithms I-SECS-1021-03
ai tools demonstartion for schools and inter college
Operating system designcfffgfgggggggvggggggggg

JavaScript patterns chapter 8 of mine

  • 1. DOM and Browser Patterns Carl 2016/02/23 1
  • 2. Outline Separation of Concerns DOM Scripting Events Long-Running Scripts Remote Scripting Deploying JavaScript Loading Strategies Summary 2
  • 4. Separation of Concerns Test without CSS/JS No inline event handlers or style(?) ReactJS JSX: <button onClick={this.test(this)}>Submit</button> Semantically HTML elements 4
  • 5. Capability Detection Check function exist instead of check browser agent // antipattern if (navigator.userAgent.indexOf('MSIE') !== −1) { document.attachEvent('onclick', console.log); } // better if (document.attachEvent) { document.attachEvent('onclick', console.log); } // or even more specific if (typeof document.attachEvent !== "undefined") { document.attachEvent('onclick', console.log); } 5
  • 7. DOM Access Avoiding DOM access in loops Assigning DOM references to local variables and working with the locals Using selectors API where available Caching the length when iterating over HTML collections (see Chapter 2) 7
  • 8. Avoiding DOM access in loops // antipattern for (var i = 0; i < 100; i += 1) { document.getElementById("result").innerHTML += i + ", "; } // better - update a local variable var i, content = ""; for (i = 0; i < 100; i += 1) { content += i + ","; } document.getElementById("result").innerHTML += content; 8
  • 9. Assigning DOM references to local variables and working with the locals // antipattern var padding = document.getElementById("result").style.padding, margin = document.getElementById("result").style.margin; // better var style = document.getElementById("result").style, padding = style.padding, margin = style.margin; 9
  • 10. Using selectors API where available document.querySelector("ul .selected"); document.querySelectorAll("#widget .class"); https://developer.mozilla.org/zh-TW/docs/Web/API/document.querySelector Faster than jQuery Dom method document.getElementById(myid) is still the fatest https://jsperf.com/getelementbyid-vs-queryselector/25 10
  • 11. DOM Manipulation(Document Fragment) // antipattern // appending nodes as they are created var p, t; p = document.createElement('p'); document.body.appendChild(p); p = document.createElement('p'); document.body.appendChild(p); 11
  • 12. DOM Manipulation(Document Fragment) var p, t, frag; frag = document.createDocumentFragment(); p = document.createElement('p'); frag.appendChild(p); p = document.createElement('p'); frag.appendChild(p); document.body.appendChild(frag); https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment 12
  • 13. DOM Manipulation(Document Fragment) var oldnode = document.getElementById('result'), clone = oldnode.cloneNode(true); // cloneNode(true) if the children of the node should also be cloned, or false to clone only the specified node. https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode // work with the clone... // when you're done: oldnode.parentNode.replaceChild(clone, oldnode); 13
  • 15. Events Handling Use addEventListener/attachEvent instead of onxxx(ex: onclick) onxxx bind to only one event 15
  • 16. Event Delegation Bind event to parent instead of child Use event.target to check the target node Pros reduce event listeners Cons hard to find the event listener from browser developer tool Demo http://codepen.io/anon/pen/vLqvaV 16
  • 17. Event Delegation ReactJS JSX: <button onClick={this.test(this)}>Submit</button> React use single top level event listener https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#under-the-hood- autobinding-and-event-delegation 17
  • 18. Long-Running Scripts (setTimeout) var timer1 = setTimeout(myfunction1, 50); var timer2 = setTimeout(myfunction2, 100); var timer3 = setTimeout(myfunction3, 150); 18
  • 19. Long-Running Scripts (Web Wrokers) var ww = new Worker('my_web_worker.js'); ww.onmessage = function (event) { document.body.innerHTML += "<p>message from the background thread: " + event.data + "</p>"; }; // Output message from the background thread: hello there message from the background thread: halfway there, `tmp` is now 3749999975000001 message from the background thread: all done 19 // my_web_worker.js var end = 1e8, tmp = 1; postMessage('hello there'); while (end) { end -= 1; tmp += end; if (end === 5e7) { // 5e7 is the half of 1e8 postMessage('halfway there, `tmp` is now ' + tmp); } } postMessage('all done');
  • 21. XMLHttpRequest var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState return false; } if (xhr.status !== 200) { alert("Error, status code: " + xhr.status); return false; } document.body.innerHTML += "<pre>" + xhr.responseText + "</pre>"; }; xhr.open("GET", "page.html", true); xhr.send(""); 21
  • 22. JSONP Not restricted by the same-domain policy (Use script tag) Often JSON wrapped in a function call https://zh.wikipedia.org/wiki/JSONP var script = document.createElement("script"); script.src = “http://remote.org/getdata.php?callback=myHandler”; document.body.appendChild(script); // Output of http://example.org/getdata.php?callback=myHandler myHandler({“hello”: “world”}); 22

Editor's Notes

  • #20: IE10才開始支援