Exploring Modern Web Development Techniques
"Explore the evolution of website development from traditional to modern approaches like AJAX, single-page applications, and managing history entries. Learn about Asynchronous JavaScript and XML, using the Fetch API, and transitioning from XMLHttpRequest to fetch in web browsers. Discover how to manipulate history entries and enhance user experience with client-side JavaScript."
Download Presentation
Please find below an Image/Link to download the presentation.
The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.
E N D
Presentation Transcript
AJAX Peter Larsson-Green J nk ping University Spring 2019
TRADITIONAL WEBSITES Header Header Menu Page A Page B Page C Menu Page A Page B Page C Content A Content B Click! page-a.html page-b.html We fetch information we already have. Takes extra time Wasting data Loading...
"MODERN" WEBSITES Single Page Application: A single HTML file, and a lot of client-side JavaScript code. Header Menu Page A Page B Page C Content A ------------ Content B Click! page-a.html Update! Fetch the content of Page B from server.
AJAX Asynchronous JavaScript and XML. In old web browsers: XMLHttpRequest In modern web browsers: fetch
THE fetch FUNCTION fetch('http://www.the-website.com/api/humans', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({name: "Alice"}) }).then(function(response){ // Got back an HTTP response }).catch(function(error){ // Something went wrong }) POST /api/humans HTTP/1.1 Host: www.the-website.com Content-Type: application/json Content-Length: 17 {"name": "Alice"}
THE fetch FUNCTION The old solution: using the XMLHttpRequest object // ... }).then(function(response){ const statusCode = response.status const contentType = response.headers.get("Content-Type") return response.json() .then(function(human){ const name = human.name }).catch(function(error){ // ... }) fetch('http://www.the-website.com/api/humans/4', { HTTP/1.1 200 OK Content-Length: 15 Content-Type: application/json {"name": "Bob"}
MANAGING THE HISTORY Header Header Menu Page A Page B Page C Menu Page A Page B Page C Content A Content B Click! page-a.html page-b.html
MANAGING THE HISTORY Add history entry: history.pushState({page: "about"}, "Title", "/about") Listen for history changes: window.addEventListener('popstate', function(event){ const state = event.state })
MANAGING THE HISTORY Example