Dynamically load scripts at runtime and verify their successful loading

My script file needs to dynamically import another script and utilize the functions and variables defined inside it.

Currently, I am adding it to the HEAD section of the Page. However, after the addition, the functions and variables from the outer script are not fully loaded and available for use. How can I ensure that the script is completely loaded?

I have attempted to use script.onreadystatechange and script.onload callbacks, but I am encountering some browser compatibility issues.

What is the safest way to achieve this with pure JS while maintaining decent browser compatibility?

Sample:

uno.js:

var script = document.createElement("script");
script.src = "dos.js";
script.type = "text/javascript";
document.getElementsByTagName("head")[0].appendChild(script);
alert(outerVariable); // undefined

dos.js:

var outerVariable = 'Done!';

sample.html

<html>
    <head>
        <script type="text/javascript" src="uno.js"></script>
    </head>
    ...
</html>

Answer №1

If you are worried about compatibility with non-IE browsers, a good approach would be to utilize DOMContentLoaded to check if the script has fully loaded.

To learn more about DOMContentLoaded, you can visit this link

Interestingly, this is similar to how JQuery operates with document ready. Here's an excerpt from the jquery source code:

    // Code snippet from jQuery source demonstrating logic for handling DOMContentLoaded event
    if ( document.addEventListener ) {
                // Use the handy event callback
                document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

                // Fallback to window.onload, which will always work
                window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
        } else if ( document.attachEvent ) {
            // ensure firing before onload,
            // maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", DOMContentLoaded );

            // Fallback to window.onload, which will always work
            window.attachEvent( "onload", jQuery.ready );

            // If IE and not a frame
            // continually check to see if the document is ready
            var toplevel = false;

            try {
                toplevel = window.frameElement == null;
            } catch(e) {}

            if ( document.documentElement.doScroll && toplevel ) {
                doScrollCheck();
            }
        }

If you're interested in learning how to implement similar functionality like JQuery, you can refer to the bind ready function in the full source code of JQuery.

Answer №2

Up to now, this method appears to be the most effective. It has been tested on IE9, Firefox, and Chrome.

Do you have any concerns?

uno.js:

function loadScript(url, callback) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    if (navigator.appName=="Microsoft Internet Explorer") {
        script.onreadystatechange = function(){
            if (script.readyState == 'loaded') {
                document.getElementsByTagName('head')[0].appendChild(script);
                callback();
            }
        };
    } else {
        document.getElementsByTagName('head')[0].appendChild(script);
        script.onload = function(){
            callback();
        };
    }
}

loadScript('dos.js', function(){
    alert(outerVariable); // "Done!"
});

Answer №3

Utilize the onload event handler in Internet Explorer versions 9 to 11, Chrome, and Firefox, or the onreadystatechange event handler in Internet Explorer versions 6 to 9.

var oScript = document.getElementById("script")
        oScript.src = "dos.js"
        if (oScript.onload !== undefined) {
            oScript.onload = function() {
                alert('load')
            }
        } else if (oScript.onreadystatechange !== undefined) {
            oScript.onreadystatechange = function() {
                alert('load2')
            }
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Next.js | Error: Attempting to access a property of an undefined value (property name: 'secret')

I encountered an issue while trying to authenticate the API routes in next.js. The page level authentication is working properly, but when attempting to fetch the session in the API routes, I am facing an error. Error - TypeError: Cannot read properties of ...

What is the correct process for authenticating requests from SSR to the Feathers JS API?

There are some examples available on how to access FeathersJS API from SSR, but the important aspect of authorizing such requests is missing. Is it feasible to create a feathers-client app for each request? Wouldn't that put too much load on the syste ...

Are you encountering difficulties while managing back pressure as anticipated when applying node request or axios in combination with streams for downloading and extracting files?

We have encountered a peculiar problem while trying to download and decompress a large file of approximately 6 GB (which decompresses to around 64 GB) using the HTTP protocol. To achieve this, we are utilizing either Node.js' request library or axios. ...

Using Node.js and Express to assign a JavaScript property to a variable

Feeling a bit lost here, struggling with the "too noob to know what to search for" syndrome. In my Node/Express app, I'm attempting to retrieve user information from a mySQL DB and pass the user's email to an Infusionsoft API. When I hardcode th ...

What could be causing the malfunction of useEffect() in my script?

const [isOpen, setIsOpen] = useState(false); useEffect(() => { if (!token) { return <Navigate to="/auth/login"/> } getMe(token) }, [token, getMe]) return ( <RootStyle> <DashboardNavbar onOpenSi ...

What is the best way to show my button only when within a specific component?

Is there a way to display the Logout button on the same line as the title only when the user has reached the Home component? In simpler terms, I don't want the logout button to be visible all the time, especially when the user is at the login screen. ...

What is the best way to implement date range filtering in vue js?

Currently, I am delving into the realm of vue.js and experimenting with a filtering feature that involves date ranges. The process goes like this: initially filter by type, then proceed to filter by a specified date range, consisting of start and end dat ...

Using JavaScript to display dynamic data pulled from Django models

I am currently in the process of designing my own personal blog template, but I have encountered a roadblock when it comes to creating a page that displays previews of all posts. This particular page consists of two columns, #content-column-left and #conte ...

Issue with AngularJS script halting when reaching factory function that returns a promise

I have been working on a beginner project that is essentially a simple task manager (similar to those todo list projects). I created a user login page for this project and here is how it functions. There are two functions, siteLogin() for logging in, and ...

Utilizing React Views in an Express Environment

I am struggling to find a simple example that demonstrates how to connect an Express.js route to render a React view. This is what I have tried so far. +-- app.js +-- config | +-- server.js +-- routes | +-- index.js +-- views | +-- index.html app. ...

How come the hidden container does not reappear after I click on it?

I'm having an issue with a hidden container that holds comments. Inside the container, there is a <div> element with a <p> tag that says "Show all comments". When I click on this element, it successfully displays the comments. However, cli ...

How do I trigger a click event without actually selecting an option in selectpicker?

When I try to select an option from the dropdown menu using selectpicker, it doesn't get selected. For instance, clicking on the "two" option doesn't actually select it. How do I fix this issue with selectpicker? Here is the code snippet: ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

Exploring the World of THREE.js: Particles and PointClouds

I am currently working on a project where I want to create orbiting objects with trails. To achieve this, I have set up a particle system using THREE Geometry, a THREE PointCloud, and a THREE PointCloudMaterial: particleMaterial = new THREE.PointCloudMate ...

Having trouble with the Aurelia JSPM install -y command not functioning properly on Windows

I am currently following the Aurelia tutorial at I am attempting to install Aurelia dependencies using Gulp and JSPM. I successfully ran "jspm install -y" without any issues. However, upon opening the browser console, I encountered the following error: ...

Can you explain the purpose of the square brackets within the ".module("modulename", [...])" syntax used in AngularJS?

I recently came across a sample demonstrating routing in AngularJS. I am curious about the connection between the dependency 'ngRoute' and the module mainApp, as shown in the syntax var mainApp = angular.module("mainApp", ['ngRoute']);. ...

What is the best way to bring a "subdependency" into ES6?

I am dealing with a situation where I have a package called react-router, which relies on another package called path-to-regexp. The challenge is that react-router does not provide its own import of path-to-regexp. So, I am wondering how I can import the e ...

Extract feedback (produced through javascript) utilizing RSelenium/XML

I am interested in extracting comments from online news sources. For instance, take a look at this article: Story I am encountering a similar issue as discussed in this thread: Web data scraping (online news comments) with Scrapy (Python) While I unders ...

Having trouble with NVM not working correctly in Ubuntu 21.04 Terminal?

Lately, I've been facing challenges with updating my Node.js version, and one method I tried was using node version manager. After downloading the install_nvm.sh file with the command curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/insta ...

Setting the date in a datetimepicker using the model

I've encountered an issue while trying to utilize the angular date time picker. It seems that when I load data from the model, the picker does not bind the value correctly. If I manually set the value to a date, it works fine. However, when the data ...