Coding for SEO: Using JavaScript to track COVID-19
An explanation of asynchronous JavaScript using Fetch API for getting JSON data to the screen.
Modern JavaScript doesn’t have to lock up the CPU main thread the way XHR does. New patterns also make it easy to request and manage JSON data. Let’s see how it can be done with a simple script that fetches COVID-19 statistics to display in your browser.
<!DOCTYPE html> | |
<html lang=”en“> | |
<head> | |
<meta charset=”utf-8“> | |
<meta name=”viewport” content=”width=device-width, initial-scale=1.0, minimum-scale=1.0“> | |
<meta http-equiv=”x-ua-compatible” content=”ie=edge“> | |
<title>US Covid-19</title> | |
<script> | |
const getCovidStats = async() => { | |
try { | |
const response = await fetch(‘https://covidtracking.com/api/us’); | |
const usa = await response.json(); | |
covid19 = usa[0]; | |
} | |
catch (err) { | |
console.log(`Error: ${err}`); | |
} | |
finally { | |
markup = ` | |
Tests: ${covid19[‘totalTestResults’]} | |
Positive: ${covid19[‘positive’]} | |
Negative: ${covid19[‘negative’]} | |
Hospitalized: ${covid19[‘hospitalized’]} | |
Deaths: ${covid19[‘death’]}` | |
document.getElementById(‘main’).innerText = markup; | |
} | |
}; | |
getCovidStats(); | |
</script> | |
</head> | |
<body> | |
<div id=”main“></div> | |
</body> | |
</html> |
Copy the source code above and paste it into a text editor. Save it as a local file on your desktop (or somewhere you’ll remember). Make sure to give it the .html
extension so that it opens easily using your web browser. Double-click the new file, or navigate to it using your browser’s [File]→[Open File] menu item.
Provided you’re connected to the Internet, you should see statistics appear on the page. Our script fetches JSON data from a source managed by several journalists and unpacks it to update your page DOM. Refresh the page or visit it periodically to track the latest statistics.
Assigning functions as values
When considering this code, skip over the opening HTML to look at what’s happening inside the script tag. The first line of JavaScript is a statement that assigns a complex value — a function — to the name “getCovidStats.”
const getCovidStats = async() => {
The assignment value is everything between the first equal sign after “getCovidStats” and the semicolon on line 28: async() => { ...};
The semicolon here terminates the value assignment.
Since the code declares an async() function, when we reference getCovidStats, we’re going to need to do so in the form for calling functions for it to work. We need to use parentheses as you see them on line 29: getCovidStats();
Notice how we named getCovidStats()
after what the function does? It’s a good idea to name functions after their primary action — labeling what our functions do — as a general naming convention. This makes it easier for future programmers to follow our code. It also makes it easier for you to follow your own code if you return to it months or years down the road.
A note about constants
The const keyword is shorthand for ‘constant,’ which is a general programming notion for a value that should not change. In this case, getCovidStats
is a constant.
JavaScript constants cannot be reassigned or redeclared without errors. JavaScript provides error messages as guard rails for us to avoid buggy code. The condition forces us to use our constants properly.
When you’re writing constant values you “hard-code” values to the variable names as if chiseling them in stone. We often write functions as constant variables because we don’t want our functions to behave unpredictably.
The async() function
Don’t sweat the =>
arrow — the body of our async()
function is bounded by a set of curly braces: {}
, opening on line 9 and closing on line 28. Notice the nested try {}
, catch {}
, and finally {}
methods which are also defined using curly braces as bounds. The code inside curly braces is what will run when these functions or methods are called.
They are called here sequentially.
Await
Our async() function introduces a special new keyword used in the try block: await. When we use async() { await { code } }
it implies a JavaScript ‘Promise’ will eventually return at some future point. Using await
won’t block processing other tasks. Other code can run while at this point we ‘await’ the return of a Promise.
Fetch API
We’re using fetch()
which returns a Promise object for the URL we designate as a required argument. Network methods such as fetch()
with Promises make good use cases, because network connectivity is totally unpredictable. We don’t want our program to stop waiting for an immediate response. We want to move on and count on the fact the Promise will return down the line.
A note about browser support
The Fetch API and async()
functions with await
are modern JavaScript patterns that aren’t always supported by old browsers, particularly non-Edge IE browsers. Heed the warning about writing code for your target market.
If you need to support old browsers then look into a deployment strategy that offers advanced features with polyfills or can gracefully decline to your lowest denominator browser.
Our covid-19 data source
The source we use is kept up by several journalists working for major news organizations. It offers us JSON responses to simple GET requests. That is ideal for our purposes.