Lazy load JavaScript?

TLDR: Yes, you can. Here: https://github.com/bingzer/js-inject/blob/main/index.js

Consider the following use-case:

Fetch and execute a JavaScript library on certain page only after a certain user’s action. One good example of this is to load CKEditor after a user’s intent to write a comment in a specific page.

This can be done by injecting <script> on the page after the intended user’s action. One thing to consider is to not re-inject if CKEditor is already loaded.

So I came up with a simple code snippet: js-inject

js-inject

js-inject contains only one function injectScript(). This function will inject <script src="..."> into document only if existsFunctions() returns a falsy

In this scenario, injectScript() will inject the CKEditor script only if window.CKEditor is not already loaded.

js-inject is a code snippet (and no, it’s not an npm package) that you can copy + paste to inject <script> after DOMContentLoaded event.

Grab it here: https://github.com/bingzer/js-inject/blob/main/index.js

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A WordPress.com Website.

Up ↑

%d bloggers like this: