How to Lazy-Load external scripts for better page speed?

Article autor
September 9, 2025
How to Lazy-Load external scripts for better page speed?
Elixir Newsletter
Join Elixir newsletter

Subscribe to receive Elixir news to your inbox every two weeks.

Oops! Something went wrong while submitting the form.

Table of contents

Nowadays, with an ever-growing number of web services, we tend to overload Web apps with external resources. As a result, it decreases page load speed and affects SEO score. There is a pretty easy solution for that.

Let's assume that you'd like to use the chatbot on your website. Fetching all resources might take in this case, for example, 2 seconds (which is not that unusual - trust me).

Even if your website is fully optimized to load fast, users will still have to wait 2 more seconds for full interaction.

In this case, if you don't need a chatbot to appear immediately, you can lazy-load the script:

setTimeout(function () {
  var d = document,
    s = d.createElement("script");
  s.src = "path-to-js-script";
  d.body.appendChild(s);
}, 5000);

That's it. After 5 seconds, a chatbot will be fetched and attached to the body of your website.

It's important to use a time interval that is long enough to run after the page is fully loaded. In this example, I used 5s interval, but you should use the one that match to your specific case.

Related posts

Dive deeper into this topic with these related posts

No items found.

You might also like

Discover more content from this category

How to safely handle related database operations with Ecto Multi

Sometimes you need to do some database operations at once. A simple example: User-A transfers money to User-B. Updating just one balance at the time creates a risk of data desynchronization. What if the first DB operation goes well but updating the second user’s data fails? Sounds like a hard to catch vulnerability.

How to run tests in Elixir IEx shell

Hey! Have you ever wondered about tests running inside the IEx shell? For a long time, I was convinced that it’s not really possible. And as it turns out - that’s not really straightforward. You won’t easily find information about that in the documentation.

How to revert commit in Git

Did you ever create a commit that you wish never happened? Let's be honest - we all did. There is an easy way to revert it in Git.