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

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
You might also like
Discover more content from this category
So you don’t know what’s the type of struct you’re passing somewhere? Maybe it can be one of few types and you have to distinguish them? Or any other reason… But it’s about checking the struct type. Just use one of the coolest Elixir features - pattern matching!
There is a common scenario: You'd like to debug your Phoenix app with break!/4 or IEx.pry/0. Everything works fine, until... Phoenix server throws a timeout error statement.
Pattern-matching is one of the finest elixir-lang features. Whoever knows the power of this tool once, will want to use it forever.
