Inject JavaScript Or CSS At Runtime And On Demand

How to load a JavaScript library, component or a style only when you really need it #OneTrickADay-32

David Dal Busco
4 min readMar 18, 2020
Photo by Aditya Saxena on Unsplash

I challenged my self to share a blog post each and every single day until end of the current quarantine in Switzerland, the 19th April 2020. Thirty-two days left until hopefully better days.

In this third blog post, I would like to share with you a trick we are using in our open source project DeckDeckGo but also one which has been shared by Cory McArthur, an incredible user experience engineer of Sworkit.

Commonly you are including your dependencies in your app bundle, but some of these might be used only in certain circumstances. For instance, if you are using Firebase UI to handle your authentication flow or if like us, you create a Web Component which act as a wrapper around another library like Prismjs, you might want to load these only when really needed.

Even though a lazy loading pattern might be use in your app, depending of your UX and routing, you might rarely face the case where such libraries are fetched even if actually not needed.

But no worries, here’s a trick to solve such requirement by injecting either a script or css in your page on demand and at runtime.

--

--