Daniel Greatman Walter
Daniel Greatman Walter

Reputation: 157

How can I execute javasript function before page load for search engine crawlers?

I am tasked with grabbing the page's title from an API. This data has to be available for web crawlers to grab. This is what I have done so far.

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta name="description" content="Test description" />
      <title>Test title</title>

      <script>
        document.addEventListener('DOMContentLoaded', function () {
          const endPoint = 'endpoint.com'
          fetch(apiEndpoint).then(function (response) {
            return response.json();
          })
          .then(function (data) {
            // change title with javascript logic
          }).catch(function() {
            // fallback title
          })
        })
      </script>
    </head>
<body></body>
</html>

Upvotes: 0

Views: 27

Answers (1)

Tony McCreath
Tony McCreath

Reputation: 3399

You don't need to delay the running of the script, as it is already after the creation of the title tag.

Google and some other search engines do render the page and will see your change as long as it does not take too long. I find 5 seconds is about the limit.

Upvotes: 0

Related Questions