DEV Community

Kumar Abhishek
Kumar Abhishek

Posted on • Originally published at abhi.page on

How to load third-party Javascript on demand | Notes

A small script to dynamically (and, asynchronously) load third-party Javascript files on demand.

  • It inserts a <script> tag in the head to load the script.
  • Checks if a <script> tag already exists with the same source to avoid duplicate script tags.
    • I use it with a Web Component based library where another component may already have loaded the script.
  • Callbacks after successful or failed load.
  • Note: I also use a retry logic (that removes and re-attaches the script tag) to avoid temporary network failures. I have not included it here for simplicity.
/**
 * @param {string} src The URL of the script.
 * @callback onLoadSuccessCallback Callback when script is loaded successfully.
 * @callback onLoadErrorCallback Callback when the script fails to load.
 */
function loadScript(src, onLoadSuccessCallback, onLoadErrorCallback) {
    if (!src) {
        console.error("Error: missing src");
        return;
    }

    // Check if the script is already loaded
    if (document.querySelector('script[src="' + src + '"]')) {
        // Script already loaded...
        console.warn("Script Already Loaded. Skipping: ", src);
        onLoadSuccessCallback();
    } else {
        // Script not already leaded; load script...
        // Create script tag
        const js = document.createElement('script');
        js.src = src;
        js.setAttribute("async", "");

        // Setup success callback
        if (onLoadSuccessCallback) {
            js.onload = onLoadSuccessCallback;
        }

        // Setup error callback
        if (onLoadErrorCallback) {
            js.onerror = onLoadErrorCallback;
        }

        // Add the script tag to <head>
        document.head.appendChild(js);
    }
};
Enter fullscreen mode Exit fullscreen mode

Use it like this:

loadScript('url/or/path/to/script.js', () => {
    console.log("Script loaded");
    // Do something with the script.
}, () => {
    console.error("Script load failed");
    // Handle error.
});
Enter fullscreen mode Exit fullscreen mode

Read on abhi.page

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay