Post on 06-Jul-2020
Client-Side Web Programming: JavaScript (Part 3)
Copyright © 2020 byRobert M. Dondero, Ph.D.
Princeton University
1
Objectives
• You will learn/review:– JavaScript libraries– Specifically, a taste of…– jQuery– React
2
Preparation
• To prepare for this lecture:– Browse to
https://www.cs.princeton.edu/courses/archive/spr20/cos333/lectures/14webjavascript/
– Download all .zip files to your local computer– Expand .zip files to yield source code files– Load source code files into your local editor– Set local editor to display line numbers
3
Motivation for JavaScript Libraries
• Problem 1:– Many incompatibilities among browsers
• DOM, JavaScript, and HTML versions may differ– JavaScript code should account for
all/most/many variations– Becoming less important
• Problem 2:– JavaScript/AJAX code uses common patterns
and often is repetitive
4
JavaScript Libraries
• Solutions:– Use a JavaScript generator
• Google Web Toolkit, …– Use a JavaScript library
• jQuery, React, …
5
JavaScript Libraries
6As of May 2019, according tohttps://divante.com/blog/top-10-popular-javascript-frameworks-2019/
Agenda
1. jQuery2. React3. Compare & contrast
7
jQuery• Who: John Resig• When: 2006• Why: Simplify
JavaScript syntax for finding, selecting, and manipulating DOM elements
8
jQuery Fundamentals
• jQuery syntax:– $(selector).action()
• $: indicates access of jQuery• selector: selects HTML element(s)
– As in CSS; covered soon• action(): specifies an action to be performed on
the selected element(s)
9
PennyJQuery App
• See PennyJQuery app
10
PennyJQuery App
• See PennyJQuery app (cont.)– runserver, runserver.bat– book.py, database.py– penny.py
11
PennyJQuery App
• See PennyJQuery app (cont.)– search.html
• Some notes...
12
PennyJQuery App• See PennyJQuery app (cont.)– search.html
• Must fetch jQuery library• Option 1
– Browser fetches jQuery library from jQuery site– Pro: Always get latest version– Pro: Likely to be cached in browser– Con: What if not cached and jQuery site is down???!!!
• Option 2 (commented out)– Ahead of time, download jQuery your to your website– Browser fetches jQuery library from your website– Con: May be stale– Pro: Always works!
13
PennyJQuery App
• jQuery makes it easier to access DOM
let author =document.getElementById('authorInput').value;
let author = $('#authorInput').val();
14
Without jQuery:
With jQuery:
# => access by id
PennyJQuery App
• jQuery makes it easy to separate event handling code from HTML
15
PennyJQuery App
function setup(){
$('authorInput').focus();…getAmPm();getDateTime();
}…$('document').ready(setup);
With jQuery(in search.html):
16
<body onload="getAmPm(); getDateTime();document.getElementById('authorInput').focus()">
Without jQuery (in search.html):
<body>
PennyJQuery App
17
<input type="text" id="authorInput" oninput="getResults()">
Without jQuery (in search.html):
function setup(){ …
$('#authorInput').on('input', getResults);…
}…$('document').ready(setup);
With jQuery(in search.html):
<input type="text" id="authorInput”>
PennyJQuery App
• jQuery makes it easy to program AJAX
18
PennyJQuery App
19
function createAjaxRequest(){ ...
return req;}function processReadyStateChange(){ ...
let resultsParagraph =document.getElementById("resultsParagraph");
resultsParagraph.innerHTML = this.responseText;}function getResults(){ ...
request = createAjaxRequest();request.onreadystatechange = processReadyStateChange;request.open("GET", url);request.send(null);
}
Without jQuery (in search.html):
PennyJQuery App
function handleResponse(response){
$('#resultsParagraph').html(response);}function getResults(){ ...
request = $.ajax({ type: "GET",
url: url,success: handleResponse
});
}
20
With jQuery (in search.html):
jQuery Summary
• jQuery summary– Useful
• Easy to access DOM• Easy to separate event handling from HTML code• Easy to use AJAX
– Easy to learn and use• Especially if you know CSS
– Extremely popular
21
Agenda
1. jQuery2. React3. Compare & contrast
22
React
• Who: Jordan Walke• When: 2011• Where: Facebook• Why: Handle user
interfaces in web apps
23
Note: React == React.js == ReactJS
React Overview
• Pgmmer defines custom ES6 classes, extending React Component class
• Pgmmer uses custom classes to instantiate custom elements
• Each custom element– Can have properties (props)– Can have state– Renders its HTML
24
PennyReact1Basic App
• See PennyReact1Basic app
25
PennyReact1Basic App
• See PennyReact1Basic app (cont.)– runserver, runserver.bat– book.py, database.py
26
PennyReact1Basic App
• See PennyReact1Basic app (cont.)– penny.py
• searchResults() returns plain text, not HTML fragment
• React will not allow insertion of HTML into results paragraph
– See description of cross-site scripting attacks in Securitylecture
27
PennyReact1Basic App
• See PennyReact1Basic app (cont.)– search.html
• Commands browser to fetch React• Defines div element with id root
– Essentially all other HTML code is generated via JavaScript
28
PennyReact1Basic App
• See PennyReact1Basic app (cont.)– search.html (cont.)
• Defines PennyHeader class– Defines PennyHeader element– Maintains state object having datetime property– Uses timer to maintain state object– Defines render() to update virtual DOM
» Uses state object» Calls React.createComponent()
– React uses virtual DOM to update browser DOM
29
PennyReact1Basic App
• See PennyReact1Basic app (cont.)– search.html (cont.)
• Defines PennyFooter class– Defines PennyFooter element– Maintains state object having datetime property– Uses timer to maintain state object– Defines render() to update virtual DOM
» Uses state object» Calls React.createComponent()
– React uses virtual DOM to update browser DOM
30
PennyReact1Basic App• See PennyReact1Basic app (cont.)– search.html (cont.)
• Defines PennySearch class– Defines PennySearch element– Maintains state object having inputValue and books
properties– Detects changes in input element to maintain state object
» Uses AJAX– Defines render() to update virtual DOM
» Uses state object» Calls React.createComponent()
– React uses virtual DOM to update browser DOM
31
PennyReact1Basic App
• See PennyReact1Basic app (cont.)– search.html (cont.)
• Generates div element containing:– PennyHeader element– PennySearch element– PennyFooter element
• Calls ReactDom.render() function– Renders div element into virtual DOM within element
whose id is root– React uses virtual DOM to update browser DOM
32
PennyReact1Basic App
• But that’s not how React apps really look…
33
PennyReact2Jsx App
• JSX (JavaScript XML)– Allows embedding of HTML-like code
(actually, XML code) in JavaScript code– No explicit calls of React.createElement()
34
PennyReact2Jsx App
• See PennyReact2Jsx app– runserver, runserver.bat– book.py, database.py– penny.py
35
PennyReact2Jsx App
• See PennyReact2Jsx app (cont.)– search.html
• Commands browser to fetch JSX• Uses JXS instead of React.createComponent()
36
PennyReact2Jsx App
• But that’s still not how React apps really look…
37
PennyReact3Real App
• The general idea:– Before run-time:
• Place React, JSX, and all JavaScript files comprising your app in a JavaScript bundle
– At run-time:• Browser requests “search” page; server delivers it• Browser requests bundle; server delivers it• Browser interprets bundle• Browser incrementally requests book lists; server
incrementally delivers them
38
PennyReact3Real App
• Thanks to Lucas Manning (‘20)…• See PennyReact3Real app
– runserver, runserver.bat– book.py, database.py– penny.py
39
PennyReact3Real App
• See PennyReact3Real app (cont.)– PennyHeader.jsx, PennyFooter.jsx,
PennySearch.jsx, main.js• Each component is defined in a distinct file
40
PennyReact3Real App
• See PennyReact3Real app (cont.)– search.html
• Minimal HTML page• Causes browser to fetch static/app.bundle.js script• Browser execution of static/app.bundle.js populates div element whose id is root
41
PennyReact3Real App
• See PennyReact3Real app (cont.)– webpack.config.js
• Configures Webpack to pack all JavaScript code into one large bundle (static/app.bundle.js)
– Includes React itself, and JSX too– Recall: search.html causes browser to fetch/execute that
bundle
42
Aside: Node.js Revisited
• Node.js– Provides tools to help with development of
React client-side• For example: Babel, Webpack• Via npm, the Node.js package manager
43
PennyReact3Real App
• See PennyReact3Real app (cont.)– init
• Creates a new npm module• Uses npm to install dependencies
– build• Uses Babel to convert JSX to JavaScript, and
transpile JavaScript from ES6 to ES5• Uses Webpack to pack all ES5 JavaScript code
into one large bundle (static/app.bundle.js)– Includes React itself, and JSX too
44
PennyReact3Real App
• To give it a try:– Install the node.js environment from
https://nodejs.org/en/– Run ./init– Run ./build– Run ./runserver 55555– Browse to http://localhost:55555
45
PennyReact3Real App
• At run-time:– Browser requests search.html; server delivers
it– Browser requests app.bundle.js; server
delivers it– Browser interprets app.bundle.js– Browser incrementally requests book lists;
server incrementally delivers them
46
React Conclusion
• There is much more to React• Next steps
– Study some richer examples• Especially examples that involve props and nested
components– Learn about React with FLUX pattern
• As implemented by the Redux library
47
React Conclusion• create-react-app
– Node.js program– Latest way to create a React app– By default:
• Browser loads React app from host h1 at port p1• Via React app, browser repeatedly contacts penny
app running on host h2 at port p2 to fetch book lists– Commentary:
• Strange!• Cookies? CAS?
48
Agenda
1. jQuery2. React3. Compare & contrast
49
JavaScript Libraries Comparison
• jQuery– HTML is primary, JavaScript is secondary– Dominant paradigm: client-side MVC
• Model = DOM, view = rendered page, controller = JavaScript code
– Typically in distinct files: HTML, JavaScript• Modularity by technologies
50
JavaScript Libraries Comparison
• React– JavaScript is primary, HTML is secondary– Dominant paradigm: OOP
• Inheritance: Components inherit from React.Component
• Composition: Components can be composed of other components
– Typically in distinct files: components• Modularity by components
51
JavaScript Libraries Comparison
• Commentary:– Is jQuery code more maintainable?
• Because of better separation of concerns?– Is React code more reusable?
• Because of encapsulated components?
52
Summary
• We have covered:– JavaScript libraries– Specifically, a taste of…– jQuery– React
53