Alongside tanking search rankings, you may encounter a Google Search Console warning about First Input Delay. After profiling page performance using Dev Tools (performance tab, CPU chart), you might find JavaScript is consuming time on the CPU main thread. That JavaScript probably contains widely supported, but older-style, XML HTTP Request (XHR) for a network resource.
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.
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.
There are scattered data sources supporting International sites that produce amazing visualizations of the outbreak. Looking at what these use for data and trying to find an open API can lead to PDF (WHO situation reports) or CSV (John Hopkins), but for simplicity here we want JSON.
More development tips for SEOs
http://feeds.searchengineland.com/~r/searchengineland/~3/t3YdlMfqT0M/coding-for-seo-using-javascript-to-track-covid-19-331209