Dynamic HTML and the browser wars → jQuery
1995 – today · 2006 – today
What changed
- Where the state lives
Dynamic HTML and the browser wars
In the page: a JavaScript array and a filter variable. Nothing is saved; a reload starts again from the code.
jQuery
In the DOM: a todo is done when its
<li>has the classdone, and the counter is found by counting elements.- How the page is rendered
Dynamic HTML and the browser wars
render()builds the whole list as one HTML string and swaps it in withinnerHTML.jQuery
The server sends the first HTML. New items are built with
$("<li>")and appended.- What happens on a change
Dynamic HTML and the browser wars
Handler attributes (
onsubmit,onclick) call global functions that change the array and callrender().jQuery
Each handler changes the elements it knows about, then
refresh()fixes the counter and the filter.- How the code is organised
Dynamic HTML and the browser wars
One script of global functions, wired to the page by attributes in the HTML. No server is involved.
jQuery
One script of event handlers. A delegated handler on
#todo-listalso covers items added later.
Why it changed
What hurt in each era along the way, and the era that came next.
Dynamic HTML and the browser wars→AJAX
The page could change itself, but it could not exchange data with the server without leaving: loading fresh data or saving a change still meant a form submission or a link and a whole new page, and everything kept in variables was gone after it. On top of that, every browser needed its own branch of the code. XMLHttpRequest and the AJAX approach let a script talk to the server in the background and update only the part of the page that changed.
AJAX→jQuery
Every browser did it a little differently. Internet Explorer 5 and 6 created the object with
new ActiveXObject("Microsoft.XMLHTTP"), Internet Explorer before version 9 attached events withattachEventinstead ofaddEventListener, and each browser had its own DOM quirks, so scripts grew long and full of browser checks. Libraries like jQuery wrapped XHR, events and the DOM in one short API that worked the same in every browser.
The same app, side by side
The main file of each version. Both apps pass the same test: same markup, same behaviour, different ideas.
The apps run in sandboxes in your browser.
Dynamic HTML and the browser wars
plain browser APIs, no library
/src/main.js · 73 lines
// DHTML era: the page changes itself in the browser. The list is a JavaScript array, and
// render() writes it into the page as one HTML string. No server is asked.
// The state is plain variables in the page: a reload starts again from these lines.
var todos = [
{ id: 1, title: "Read the docs", done: true },
{ id: 2, title: "Write the app", done: false }
];
var nextId = 3;
var filter = "all";
var FILTERS = ["all", "active", "done"];
// The text the user typed becomes part of the HTML, so it is escaped first.
function escapeHtml(text) {
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
function render() {
var html = "";
var left = 0;
var i, todo;
for (i = 0; i < todos.length; i++) {
todo = todos[i];
if (!todo.done) left++;
if (filter == "all" || (filter == "done") == todo.done) {
// The handler is part of the string: onclick calls a global function with the id.
html += '<li' + (todo.done ? ' class="done"' : '') + '><label>' +
'<input type="checkbox" data-toggle onclick="toggleTodo(' + todo.id + ')"' +
(todo.done ? ' checked' : '') + '> ' +
'<span class="title">' + escapeHtml(todo.title) + '</span></label></li>';
}
}
// innerHTML throws the old items away and builds new ones, so a focused checkbox loses focus.
document.getElementById("todo-list").innerHTML = html;
document.getElementById("todo-count").innerHTML = left + " left";
for (i = 0; i < FILTERS.length; i++) {
document.getElementById("filter-" + FILTERS[i]).className = FILTERS[i] == filter ? "selected" : "";
}
}
function addTodo() {
var field = document.getElementById("new-todo");
var title = field.value.replace(/^\s+|\s+$/g, "");
if (title != "") {
todos.push({ id: nextId++, title: title, done: false });
field.value = "";
render();
}
// false cancels what the browser would do next: send the form and load a new page.
return false;
}
function toggleTodo(id) {
for (var i = 0; i < todos.length; i++) {
if (todos[i].id == id) todos[i].done = !todos[i].done;
}
render();
}
function setFilter(name) {
filter = name;
render();
}
// A <script> of the time ran in the global scope: every function above became global, and
// the onclick attributes could call it. The lab runs each file as a module with its own
// scope, so the functions the markup calls are put on window by hand.
window.addTodo = addTodo;
window.toggleTodo = toggleTodo;
window.setFilter = setFilter;
// Like a <script> at the end of <body>, this runs when the elements already exist: draw the list.
render();jQuery
jQuery 4.0.0
/src/main.js · 52 lines
// jQuery era: the page itself is the state. Handlers read the DOM, change it, recount.
import $ from "jquery";
// $(fn) waits until the document is ready, like $(document).ready(fn).
$(function () {
let filter = "all";
// Brings the counter, the visible items and the filter buttons in line with the DOM.
function refresh() {
const left = $("#todo-list li").not(".done").length;
$("#todo-count").text(left + " left");
$("#todo-list li").each(function () {
const done = $(this).hasClass("done");
$(this).toggle(filter === "all" || (filter === "done") === done);
});
$("[data-filter]").removeClass("selected");
$('[data-filter="' + filter + '"]').addClass("selected");
}
$("#todo-form").on("submit", function (event) {
event.preventDefault();
const title = String($("#new-todo").val()).trim();
if (!title) return;
// Build the new <li> the same way the server wrote the first ones.
const $item = $("<li>").append(
$("<label>").append(
$('<input type="checkbox" data-toggle>'),
" ",
$('<span class="title">').text(title),
),
);
$("#todo-list").append($item);
$("#new-todo").val("");
refresh();
});
// One delegated handler on the list also covers the items added later.
$("#todo-list").on("change", "[data-toggle]", function () {
$(this).closest("li").toggleClass("done", this.checked);
refresh();
});
$(".filters").on("click", "[data-filter]", function () {
filter = $(this).data("filter");
refresh();
});
refresh();
});