• No results found

JavaScript. MPRI : Web Data Management. Antoine Amarilli 1/49

N/A
N/A
Protected

Academic year: 2021

Share "JavaScript. MPRI : Web Data Management. Antoine Amarilli 1/49"

Copied!
60
0
0

Loading.... (view fulltext now)

Full text

(1)

JavaScript

MPRI 2.26.2: Web Data Management

Antoine Amarilli

(2)

POLL: Client-side technologies

Find the odd one out!

• A: Java

• B: JS

• C: ECMAScript

• D: JavaScript

(3)

POLL: Client-side technologies

Find the odd one out!

• A: Java

• B: JS

• C: ECMAScript

• D: JavaScript

(4)

Motivation

• Dynamic changes on the client without refreshing the page

• Simple cases: form validation, menus, etc.

→ going beyond what HTML and CSS allow

→ being compatible with old browsers

• Complex cases: writing entire in-browser applications in JS (aka single page applications , SPA)

• The language of the Web is JavaScript (ECMAScript standard)

→ Beware, it’s unrelated to Java !

(5)

Table of Contents

Introduction

JavaScript

JavaScript and HTML AJAX

Front-end Javascript frameworks

Old and new technologies

(6)

POLL: Using Javascript

Which proportion of the 10 million most visited websites use Javascript?

• A: Less than 90%

• B: Between 90% and 95%

• C: Between 95% and 98%

• D: Over 98%

(7)

POLL: Using Javascript

Which proportion of the 10 million most visited websites use Javascript?

• A: Less than 90%

• B: Between 90% and 95%

• C: Between 95% and 98%

• D: Over 98%

(8)

The JavaScript language

• ECMAScript : name of the standard (ECMA-262, 2011, 258 pages)

• JavaScript is a full-featured programming language!

• It is interpreted (traditionally) and high-level

• Dynamic typing

→ at runtime

→ typing of values, not of variables (like Python)

→ implicit conversions are very flexible (too flexible?)

• Dynamic code execution with eval

(9)

Evolution of JavaScript

• 1999: ECMAScript 3, addition of regexps , try/catch

• 2009: ECMAScript 5, addition of strict mode

• ES2015: addition of classes , iterators , generator expressions , promises, arrow functions

• ES2017: ECMAScript 8, adds atomics , async / await , etc.

• ES2018: asynchronous loops, promises extensions, regexp extensions (e.g., named capture groups)

→ Polyfills: implement new features in old language versions for legacy browsers

→ Style guides for JavaScript, e.g., Google

1

, AirBNB

2

1

https://google.github.io/styleguide/javascriptguide.xml

(10)

JavaScript language (cont’d)

• Object-oriented language, with prototypes (cloning existing objects) rather than classes

• First-class functions (anonymous functions, closures; functions are also objects)

• Support for exceptions

• Object syntax :

• foo.a for member a of object foo

• foo.b(arg) to call method b of foo with argument arg

(11)

JavaScript example

function factorial(n) {

if (n === 0) {

return 1;

}

return n * factorial(n - 1);

}

(12)

POLL: Javascript engine for Node.js

The Javascript engine used by Node.js is the one of...

• A: Internet Explorer

• B: Chrome

• C: Firefox

• D: Safari

(13)

POLL: Javascript engine for Node.js

The Javascript engine used by Node.js is the one of...

• A: Internet Explorer

• B: Chrome

• C: Firefox

• D: Safari

(14)

JavaScript engines

IE Chakra, open-sourced in 2016, since IE9

Firefox SpiderMonkey, free and open-source, released in 1996 Chrome V8, released with Chrome in 2008

→ Also used by Opera and Node.js Safari JavaScriptCore aka Nitro (2008)

→ Active research area to improve performance !

→ Just-in-time compilation ; not just interpreted

→ Some Javascript fragments are heavily optimized and used as

compilation targets (asm.js, WebAssembly, ...)

(15)

Newer Javascript dialects

• TypeScript: Javascript with optional static typing

→ The main language of the Angular framework

• Also: CoffeeScript : adds syntactic sugar (matching, etc.)

• These languages can be transpiled to Javascript

(16)

Table of Contents

Introduction JavaScript

JavaScript and HTML AJAX

Front-end Javascript frameworks

Old and new technologies

(17)

Integrating Javascript in HTML

• A bit like CSS :

<head>

<script src="script.js" type="text/javascript">

</script>

</head>

• External dependency , and security risk with third-party codes!

• The code can also go directly in <script>

• Events like onclick (explained later)

• Also links starting with javascript:

→ Beware, some browsers do not support Javascript! (e.g., robots)

It’s better not to require it if possible

(18)

Document Object Model

<html lang="fr">

<head>

<title>Titre</title>

</head>

<body>

<p>

My nice page.

</p>

</body>

</html>

html

body p My nice page.

head title

Titre

@lang

fr

(19)

The document object

The document object represents the current document:

document.documentElement Get the root node

document.getElementById("foo") Get the node with attribute id="foo" (or null if none exists)

document.getElementsByTagName("p") Return a table of all <p>

nodes

(20)

Node objects: basics

The Node objects represent nodes in the DOM tree:

node.nodeName Name of the element (BODY...) or attribute

node.nodeType Type, e.g., Node.ELEMENT_NODE, or TEXT, ATTRIBUTE, COMMENT...

node.nodeValue Value of text and attribute nodes (also:

node.setAttribute("name", "value") and node.getAttribute("name") )

node.className Node class

node.style CSS style with the various properties (with dashes replaced by camelCase). For instance:

node.style.borderStyle = "solid"

(21)

Node objects: traversal

node.parentNode The parent node

node.childNodes Array of child nodes (or null if none) node.appendChild(child) Add a child (at the end) node.removeChild(child) Remove a child

node.cloneNode(true) Clone the node and its descendants

• The new clone is not yet added to the document

• Beware of duplicate ids!

node.cloneNode(false) Clone the node (but not its descendants) node.innerHTML Get/set an HTML representation of the node

contents

(22)

The window object

By default, the methods of window are in global scope:

alert("x") Message dialog showing "x"

back() Go to the previous page

a = open("URL", "name") Open a window (or tab) on "URL" with name "name"

t = setTimeout("f()", 42000) Call f() in 42 seconds, e.g.,

• for animations

• for polling

(23)

Events

• Attribute onfoobar="return f(this)" on x:

→ When foobar happens on element x, call f(x)

• Many events . The most useful:

onclick When a click happens; return False to cancel onchange When the contents of a field change

onfocus When an element gets focus

onsubmit When a <form> is submitted; cancellable onload On <body>: when the page is done loading onmouseover When the element is hovered

onresize When the window is resized

(24)

Example: form validation

function vrf() {

v1 = document.getElementById("pw1").value;

v2 = document.getElementById("pw2").value;

if (v1 != v2) {

window.alert("The passwords don't match!");

return false;

} }

<form action="test.php" method="post" onsubmit="return vrf()">

<input type="text" name="name" placeholder="Name" required><br>

<input type="password" name="pw1" id="pw1"

placeholder="Password" required><br>

<input type="password" name="pw2" id="pw2"

placeholder="Retype password" required><br>

<input type="submit">

</form>

(25)

Table of Contents

Introduction JavaScript

JavaScript and HTML

AJAX

Front-end Javascript frameworks

Old and new technologies

(26)

Asynchronous queries

• JavaScript can also do HTTP queries

• AJAX: Asynchronous JavaScript And XML

• Exchange data with the server without reloading

• Asynchronous means that queries are not blocking

(27)

POLL: Introduction of AJAX

Which Web browser introduced AJAX?

• A: Netscape

• B: Opera

• C: Firefox

• D: Internet Explorer

(28)

POLL: Introduction of AJAX

Which Web browser introduced AJAX?

• A: Netscape

• B: Opera

• C: Firefox

• D: Internet Explorer

(29)

POLL: AJAX security

AJAX code running on a page can make requests...

• A: Only to the same page

• B: Only to the same Website

• C: To any Website

• D: It’s more complicated than that...

(30)

POLL: AJAX security

AJAX code running on a page can make requests...

• A: Only to the same page

• B: Only to the same Website

• C: To any Website

• D: It’s more complicated than that...

(31)

History and problems of AJAX

• Introduced in Internet Explorer 5 in 1999, standardised by W3C (Working Draft, 2012)

• Security implications:

• Same-origin policy : you cannot query a different domain (otherwise, danger!)

• Special mechanisms for exceptions: postMessage between clients,

Cross-Origin Resource Sharing

(32)

Example XMLHttpRequest

// Caution, not compatible with old IE versions var req = new XMLHttpRequest();

req.onreadystatechange = function() {

if (req.readyState === 4) { // is it ready?

if (req.status === 200) { // did it go well?

window.alert("Received: " + req.responseText);

} else {

window.alert("Problem with the query");

} } }

// true to be asynchronous, t to avoid caching var t = new Date().getTime();

req.open("GET", "data.xml?t=" + t, true);

// can provide POST content (which you must encode)

(33)

POLL: JSON

The JSON specification is

• A: Less than 20 pages long

• B: Between 20 and 50 pages long

• C: Between 50 and 200 pages long

• D: Over 200 pages long

(34)

POLL: JSON

The JSON specification is

• A: Less than 20 pages long

• B: Between 20 and 50 pages long

• C: Between 50 and 200 pages long

• D: Over 200 pages long

(35)

XML and JSON

• Generally, AJAX is not used to retrieve a Web page but to retrieve XML or JSON

• The Javascript code will parse it and update the page accordingly

• See next week for details about XML and JSON

(36)

Pushing data from the server

• AJAX allows us to query the server, but doesn’t allow the server to push data

• Legacy solutions:

• Polling: query periodically (latency, wasteful)

• Comet: make a request and wait for an answer, the server waits until something new has arrived

• Current solution: WebSocket IETF, RFC 6455, 2011

• Upgrade the HTTP connection to be bidirectional

• Backwards-compatibility is tricky (proxies, caches...)

→ Javascript library: socket.io

• Alternative solution: Server-Sent Events (not in IE)

(37)

POLL: BigBlueButton

The BigBlueButton chat uses...

• A: Polling

• B: Comet

• C: WebSocket

• D: Something else

(38)

POLL: BigBlueButton

The BigBlueButton chat uses...

• A: Polling

• B: Comet

• C: WebSocket

• D: Something else

(39)

Table of Contents

Introduction JavaScript

JavaScript and HTML AJAX

Front-end Javascript frameworks

Old and new technologies

(40)

POLL: jQuery market share

Which proportion of the 10 million most visited websites uses jQuery?

• A: Less than 25%

• B: Between 25% and 50%

• C: Between 50% and 75%

• D: Over 75%

(41)

POLL: jQuery market share

Which proportion of the 10 million most visited websites uses jQuery?

• A: Less than 25%

• B: Between 25% and 50%

• C: Between 50% and 75%

• D: Over 75%

(42)

jQuery

• Released in 2006

• About 87 kB

• Free and open-source (MIT)

• Used by 77% of the most visited websites.

3

• Makes it simpler to write Javascript

• Abstract away some browser quirks

3

(43)

Example jQuery

<script type="text/javascript" src="jquery-3.3.1.min.js">

</script>

<script type="text/javascript">

$.ajax({

url: "data.json", cache: false,

success: function (data) {

$( "#load" ).html( data.load );

$( "#speed" ).html( data.speed );

} });

</script>

(44)

General utility libraries

• Backbone.js , lightweight frontend JS framework

• Underscore.js , utility library for Backbone.js

• Lodash , successor of Underscore.js

• Modernizr , test which features are supported by the browser

• etc.

(45)

Angular

• AngularJS (version 1): a Javascript library

• Angular (version 2): a platform based on TypeScript

• Basic idea: update the view in a declarative way by specifying the link between the model and the view:

• one direction: when the value changes, update the view

• other direction: when the view is changed by the user, update the

value

(46)

Templates

• Idea: instantiate HTML snippets with variable values provided by Javascript

• Several languages, e.g., Mustache , Handlebars ,

<script id="entry-template" type="text/x-handlebars-template">

<div class="entry">

<h1>{{title}}</h1>

<div class="body">

{{body}}

</div>

</div>

</script>

(47)

React.js (Facebook)

• Allows you to create HTML directly in Javascript with JSX function getGreeting(user) {

if (user) {

return <h1>Hello, {formatName(user)}!</h1>;

}

return <h1>Hello, Stranger.</h1>;

}

• Virtual DOM: don’t manipulate the DOM (slow) but a copy of it, and do a tree diff to update the real DOM

• Data flow with Redux

→ More alternatives: Vue.js, Ember.js

(48)

Widget libraries

• Collections of widgets: jQuery UI , jQWidgets , Polymer , Angular Material , etc.

• Rich text editing: TinyMCE

• Tooltips: Popper

• Data visualization and plotting: D3.js

→ Bind data to visualizations

→ Define rules to update the view when elements are updated/added/deleted

• Also: Web Components (in-browser)

• Support for templates and includes

• Shadow DOM to limit the scope of embedded components

(49)

Development tools

• Developer tools in Web browsers

• JSFiddle: share and test Javascript snippets

• Github gists

(50)

Table of Contents

Introduction JavaScript

JavaScript and HTML AJAX

Front-end Javascript frameworks

Old and new technologies

(51)

POLL: Flash support on websites

Which proportion of the 10 million most visited websites still uses Flash?

• A: Less than 5%

• B: Between 5% and 10%

• C: Between 10% and 20%

• D: Over 20%

(52)

POLL: Flash support on websites

Which proportion of the 10 million most visited websites still uses Flash?

• A: Less than 5%

• B: Between 5% and 10%

• C: Between 10% and 20%

• D: Over 20%

(53)

POLL: Flash support in browsers

Which proportion of Web browsers still supports Flash?

• A: Less than 25%

• B: Between 25% and 50%

• C: Between 50% and 75%

• D: Over 75%

(54)

POLL: Flash support in browsers

Which proportion of Web browsers still supports Flash?

• A: Less than 25%

• B: Between 25% and 50%

• C: Between 50% and 75%

• D: Over 75%

(55)

Old technologies (not supported on mobile)

• Flash: released in 1996 by Macromedia (bought by Adobe), used for videos, video games, etc.

• Still used on 3% of the most popular websites

4

• In 2019, only supported by 21% of Web browsers

5

• No support on mobile , deprecated in 2017

• Java applets: released in 1995 , rich applications but no

interaction with the rest of the page: only on < 0.1% of the most popular websites

6

• Old Microsoft technologies : ActiveX, Silverlight, etc.

4https://w3techs.com/technologies/overview/client_side_language/all

5

https://www.zdnet.com/pictures/

2019s-tech-security-and-authentication-trends/2

(56)

New technologies

<canvas> Page region with efficient bitmap drawing in Javascript, useful for video games

SVG+JS Javascript manipulation of vector graphics WebGL Javascript API for accelerated 3D using a GPU WebRTC Voice and video communication across browsers

Offline Web applications that can be used offline

(57)

POLL: WebVR

What is the use of the WebVR API?

• A: To connect Vue.js and React.js

• B: To define virtual reality scenes

• C: To fly drones from Web pages

• D: To specify the visual rendering of Web pages

(58)

POLL: WebVR

What is the use of the WebVR API?

• A: To connect Vue.js and React.js

• B: To define virtual reality scenes

• C: To fly drones from Web pages

• D: To specify the visual rendering of Web pages

(59)

Web development outside the Web

• Creating Web applications and porting them to other platforms

• Apache Cordova for mobile: embed the app in a Web View

• Also: React Native

• Firefox OS (abandoned)

• Fork KaiOS: second most popular Web platform in India (after Android)

7

• Electron: bundle the app with Node.js and Chromium

→ Advantage: portability (don’t need to develop multiple apps)

→ Drawback: performance

(60)

Crédits

• Matériel de cours inspiré de notes par Pierre Senellart

• Merci à Pablo Rauzy et à Pierre Senellart pour leur relecture

References

Related documents

CEMOVIS, cryo-EM of vitri fied specimens; CET, cryo-electron tomography; CTF, contrast transfer function; DEDs, direct electron detector devices; DQE, detective quantum ef ficiency;

The corrosion current density, icorr, is observed to decrease with the increase of Al composition in the Mg sample, corresponding to the increase in corrosion resistance due to

To overcome this, disciplinary relevance was built into the program using three strategies: close collaboration between the program leader and the science discipline

4) Run the script to evaluate and plot the normal stress distribution in the region immediately around the right-hand model fault tip (this is the so-called ‘near-tip’ field).

H411 - Toxic to aquatic life with long lasting effects H317 - May cause an allergic skin reaction H319 - Causes serious eye irritation H302 - Harmful if swallowed H318 -

Gempo Jampel, Deputy Manager attached with Rural Electrification Department is awarded Asian Development Bank Government of Japan Scholarship Program (ADB) to study the

As the segment threshold increases (above 0.5% for daily and 1% for weekly), both daily and weekly data perform better; however, the performance of weekly data is less