Load Javascript

Dynamically injects a javascript file into a page or adds elements using the <script> tag.


When to use it?

Dynamically injecting a JavaScript file into a page or adding elements using the <script> tag is a technique that can be particularly useful in several scenarios. This approach allows developers to load scripts on-demand, which can significantly improve the performance of a web application by reducing the initial load time.

For instance, if a particular feature of a website, such as a complex interactive chart or a third-party widget, is only needed under certain conditions or after user interaction, it makes sense to load the related JavaScript file dynamically rather than loading it upfront with the rest of the page content.

By loading JavaScript files as and when they’re needed, you facilitates lazy loading of modules or components, which can lead to a more responsive user experience, especially on devices with limited resources or slower internet connections.

How To use it?

Given that this operation utilizes async/await, it must be encapsulated within a promise.

Example with Async

(async () => {
    try {
        await bstf.loadScript({
            url: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js',
            appendTo: 'head'
            attributes: ["id=jquery","data-test=1"],
        });
        console.log('Jquery loaded successfully.');
    } catch (error) {
        console.error(error);
    }
})();

Inline Script

Sometimes you might need only to add an inline script instead of loading one from a URL. In such cases, you can replace the url with inlineScript.

await bstf.loadScript({
    inlineScript: `console.log('This is inline script execution.');`, 
    appendTo: 'head'
});

Configuration options

  • url string The URL of the script to load.

  • inlineScript: string javascript script to execute.

  • attributes: array An array of strings representing additional attributes to set on the script element. Each attribute can be in the form of “key=value” or just “key” for boolean attributes.

  • appendTo (string | Element) Optional. Specifies the element to which the script element will be appended. Can be a selector string (‘head’, ‘body’), or a DOM element reference. Defaults to ‘head’.

Real World Examples

⚠️

Under construction