A
A
Alexander2020-12-08 12:37:12
Frontend
Alexander, 2020-12-08 12:37:12

How to correctly connect an external JS library so that it is loaded only after the entire html page is loaded?

I use the google recaptcha JS library on my site, I noticed that because of it the page loading speed drops.

How to correctly connect an external JS google library so that it is loaded only after loading the entire html page and styles, speed up page loading so that all html and styles are loaded and only then the google library is connected?

Is it possible to include an external JS library on the onload event?

Now I have a link to the google library connected in this way:

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

I registered the async defer attributes in the link, but still, the page load speed drops because of this library. The link itself is at the bottom of the page. As I understand it, defer - indicates to download in parallel with the rest of the content and execute in order immediately before the DOMContentLoaded event

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tim, 2020-12-08
@Tim-A-2020

window.onload = function() {
  const script = document.createElement('script');
  script.src = 'https://www.google.com/recaptcha/api.js';
  script.async = 1;
  script.defer = 1;
  document.body.append(script);
}

A
Alex, 2020-12-08
@Kozack

At the very bottom of the page, write a script that, on the window.onload event, inserts a captcha script tag into the document.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question