DEV Community

Cover image for What is JavaScript SEO, and Why You Should Care?
Cyril Muchemi
Cyril Muchemi

Posted on

What is JavaScript SEO, and Why You Should Care?

What is JavaScript SEO?

While JavaScript can be a powerful tool for creating engaging and interactive websites, it may present challenges for search engines in indexing and ranking those websites. Here is where JavaScript SEO comes in. JavaScript SEO is the process of optimizing a website that uses JavaScript so that it can be easily crawled and indexed by search engines.

Examples of JavaScript SEO

Here are a few examples of code snippets that you can use to improve the SEO of your JavaScript-powered website:

1. Dynamic rendering

Dynamic rendering is a technique used to serve different versions of a web page to different users. The most common use case is serving a static HTML page to search engine crawlers while serving a fully JavaScript-rendered version of the same page to regular users. Dynamic rendering is done to improve the search engine optimization (SEO) of a JavaScript-heavy website.

The main idea behind dynamic rendering is that search engines need help indexing and understanding pages fully rendered on the client side using JavaScript. By providing a static HTML version of the page, search engines can easily index the content and understand the page's structure.

On the other hand, regular users who access the page with a JavaScript-enabled browser will see the fully-rendered version with all the interactive features. Dynamic rendering allows for a better user experience while providing search engines with the necessary information to index the page.

const express = require("express");
const React = require("react");
const renderToString = require("react-dom/server").renderToString;
const App = require("./App"); // import your React component

const app = express();

app.get("/", (req, res) => {
    // render the React component to a string
    const content = renderToString(<App />);
    // check if the request is coming from a search engine
    const isFromSE = req.headers["user-agent"].includes("Googlebot");
    if (isFromSE) {
        // if the request is coming from a search engine, send the static HTML
        res.send(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>JavaScript SEO</title>
            </head>
            <body>
                <div id="root">${content}</div>
            </body>
            </html>
        `);
    } else {
        // if the request is coming from a regular user, send the full JavaScript-rendered version
        res.send(`
            <!DOCTYPE html>
            <html>
            <head>
                <title>JavaScript SEO</title>
            </head>
            <body>
                <div id="root">${content}</div>
                <script src="/bundle.js"></script>
            </body>
            </html>
        `);
    }
});

app.listen(3000, () => {
  console.log("Dynamic rendering app listening on port 3000!");
});

Enter fullscreen mode Exit fullscreen mode

This code uses the Express web framework to handle HTTP requests and the React library to create a reusable component for the application. The renderToString function from react-dom/server is used to render the React component on the server and return the resulting HTML as a string.

The resulting HTML is then sent as a response to the client's browser, allowing the JavaScript and React code to be executed and the content to be displayed.

The code checks if the request is coming from a search engine by checking the user agent in the headers, and if it is, it sends the static HTML version of the page, which the search engine can index.

If the request is from a regular user, the full JavaScript-rendered version of the page is sent, including the script '/bundle.js' that runs the react code on the client side. However, it is important to note that this is not the only way of implementing dynamic rendering. There are other methods like pre-rendering and hybrid rendering

2. Lazy loading

Lazy loading is a technique used to improve the performance of web pages by loading only the necessary resources as the user interacts with the page. It works by only loading the content currently visible or needed by the user and postponing the loading of other content until it is needed.

Lazy loading reduces the page's initial load time and improves the website's overall performance. For example, when a user visits a website with many images, lazy loading can only load the images currently visible on the screen and postpone loading images below the fold.

As the user scrolls down the page, the images that come into view will be loaded on demand, improving the overall user experience.
This technique can be applied to images and other resources like videos, audio files, and JavaScript modules. It can be implemented using various libraries and frameworks like React, Angular, Vue.js, etc.

Here is an example of lazy loading for JavaScript SEO using React and the React Router library.

import React, { Suspense } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

const Home = React.lazy(() => import("./Home"));
const About = React.lazy(() => import("./About"));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/about" component={About} />
        </Switch>
      </Suspense>
    </Router>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

This code uses React Router library to handle client-side routing and the Suspense component from React to lazy-load the Home and About components. The lazy function is used to import the components when they are needed dynamically. The fallback prop of the Suspense component is used to display a loading message while the components are being imported.

When the user navigates to the / or /about routes, the corresponding components will be imported and rendered on the page. This approach allows the JavaScript code to be loaded on-demand, reducing the initial load time and improving the application's overall performance.

It is important to note that you will need to configure your server to handle the dynamic import of the components.

3. Server-side rendering

Rendering the content of a page on the server rather than in the client's browser. Server-side rendering can improve the performance of your website, especially for users with slower internet connections. To implement server-side rendering, you must use a server-side language like PHP, Ruby, or Python.

Here is an example of server-side rendering using React and Node JS

const express = require("express");
const React = require("react");
const renderToString = require("react-dom/server").renderToString;
// import your React component
const App = require("./App"); 

const app = express();

app.get("/", (req, res) => {
  const content = renderToString(<App />);
  res.send(`
    <!DOCTYPE html>
    <html>
    <head>
      <title>JavaScript SEO</title>
    </head>
    <body>
      <div id="root">${content}</div>
      <script src="/bundle.js"></script>
    </body>
    </html>
  `);
});

app.listen(3000, () => {
  console.log("Server-side rendering app listening on port 3000!");
});

Enter fullscreen mode Exit fullscreen mode

This code uses the Express web framework to handle HTTP requests and the React library to create a reusable component for the application. The renderToString function from react-dom/server is used to render the React component on the server and return the resulting HTML as a string.

The resulting HTML is then sent as a response to the client's browser, allowing the JavaScript and React code to be executed and the content to be displayed. The script '/bundle.js' is then loaded, and it will run the react code on the client side.

Conclusion

In conclusion, JavaScript SEO is an ever-evolving field, and as web developers, it's essential to stay up-to-date with the latest techniques and best practices. Implementing server-side rendering, dynamic rendering, and lazy loading can go a long way in improving the SEO of your JavaScript-heavy website.

But remember, SEO is not just about making sure search engines can crawl and index your website; it's also about creating a great user experience. As you optimize your website for search engines, remember to keep your users in mind.

Ultimately, it's all about striking a balance between providing search engines with the necessary information to index your website and providing your users with a seamless and enjoyable experience. With the right approach, your JavaScript-heavy website can rank well in search engines and provide a great user experience.

Top comments (0)