Verify if the script has already been loaded. If not, proceed to load it asynchronously

I'm currently working on implementing an asynchronous method to load jQuery JS and then execute callback functions once it is fully loaded. I anticipate using this code repeatedly, so I want to ensure that jQuery (or any other script) is not duplicated before adding it. If the script is already in the process of loading or has been loaded, I aim to append the current call's callback to the previous one. This is my approach.

/*BP Asynchronous JavaScript Loader*/
if (typeof bp_onload_queue == 'undefined') var bp_onload_queue = [];

if (typeof bp_dom_loaded == 'boolean') bp_dom_loaded = false;
else var bp_dom_loaded = false;

if (typeof bp_async_loader != 'function') {
    function bp_async_loader(src, callback, id) {

        var script = document.createElement('script');
        script.type = "text/javascript";
        script.async = true;
        script.src = src;
        script.id = id;
        //Check if script previously loaded.
        var previous_script = document.getElementById(id);
        if (previous_script) if (previous_script.readyState == "loaded" || previous_script.readyState == "complete") {
            callback();
            alert("had already loaded the same script completely");
            return;
        } else {

            script = previous_script;
        }
        if (script.onload != null) previous_callback = script.onload;
        script.onload = script.onreadystatechange = function() {
            var newcallback;
            if (previous_script && previous_callback) newcallback = function() {
                previous_callback();
                callback();
            };
            else newcallback = callback;
            if (bp_dom_loaded) {
                newcallback();
            } else bp_onload_queue.push(newcallback);
            // clean up for IE and Opera
            script.onload = null;
            script.onreadystatechange = null;
        };
        var head = document.getElementsByTagName('head')[0];
        if (!previous_script) head.appendChild(script);
        else alert("had already started loading that script but not complete.so we appended to the previous script's callback");

    }
}

if (typeof bp_domLoaded != 'function') function bp_domLoaded(callback) {
    bp_dom_loaded = true;
    var len = bp_onload_queue.length;
    for (var i = 0; i < len; i++) {
        bp_onload_queue[i]();
    }
} 
/*JS gets loaded here */

bp_domLoaded();

/*Loading jQuery Asynchronously */
bp_async_loader("http://code.jquery.com/jquery-1.4.4.js", function() {
    alert("script has been loaded : 1");
}, "jQueryjs");

bp_async_loader("http://code.jquery.com/jquery-1.4.4.js", function() {
    alert("script has been loaded : 2");
}, "jQueryjs");

If there are any suggestions for improvement or errors in this code, please feel free to share.

Answer №1

While on the hunt for something comparable, I stumbled upon this

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

Empty return values when selecting multiple options

I'm currently facing an issue with my multiple select listbox in a form. Even though I can add items to the listbox successfully, when I submit the form, they are returned as null. What's strange is that if I manually select the items before subm ...

Why is my React Native button's onPress event not functioning correctly?

I am encountering an issue with the onPress event handler. I have tried multiple solutions but none seem to work with the handleClick function. Here are the different approaches I attempted: onPress={this.handleClick} onPress={this.handleClick()} onPress= ...

Use JavaScript and PHP to retrieve a value from an array and dynamically populate select options based on that value

In my PHP code, I have two arrays structured like this: Array ( [0] => 11 [1] => 11 [2] => 11 [3] => 11 [4] => 11 [5] => 187 ) Array ( [0] => 118 [1] => 112 [2] => 85 [3] => 81 [4] ...

Ajax continues to repeatedly redirect to the PHP page

I currently have a Shopify store and I am looking to incorporate a form on the product page. However, I am facing an issue where when I try to submit the form using AJAX with an external link, it redirects to the external page instead of staying on the cur ...

Can context be passed into a component that is created using ReactDOM.render()?

TL;DR In this given example code: ReactDOM.render(<MyComponent prop1={someVar} />, someDomNode); Can one manually provide React context to the instance of MyComponent? This might seem like an unusual question considering React's usual behavio ...

What is the best way to arrange an array of objects based on a specific attribute?

Ordering object based on value: test": [{ "order_number": 3, }, { "order_number": 1, }] Is there a way to arrange this so that the object with order_number 1 appears first in the array? ...

Storing user input in MongoDB after encoding

I am currently exploring the most effective methods for storing and presenting user input in MongoDB. In traditional SQL databases, it is necessary to encode all user input as a precaution against injection attacks. However, in the context of MongoDB, ther ...

Guide on redirecting a user to a different path when their token has expired

I am currently working on a project to create a simple website, and I am facing an issue with redirecting the user to a login page if their token has expired. I have attempted to solve this using React-JWT, but I am unsure of the proper way to do it. Here ...

"The error message "Node JS, MYSQL connection.query is not a valid method" indicates

db_config.js: const mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'test' }) connection.connect(function(err) ...

Is it possible to incorporate dynamic variables into the directives of a nested loop? Plus, thoughts on how to properly declare variables in a node.js environment

Question Explanation (Zamka): <----------------------------------------------------------------------------------------------------------> Input Example: 100 500 12 1st Line: represents the left bound (L) 2nd Line: represents the right bound ...

Automated Testing with Robot Framework: Utilizing Javascript to Click on a Button

Inspecting the web page <span jsslot=""> <button class="LkLjZd ScJHi IfEcue HPiPcc KXT7c" jsaction="click:yTqzwd" jsname="HxVe9c" autofocus="">Click Here</button> </span> I am tryin ...

Retrieve the JSON response from the server and store it in variables using jQuery's AJAX function with the `done

I am trying to retrieve a JSON response from the server upon clicking a button and then parse it into a div. However, I am struggling with how to accomplish this. <button type="submit" id="btPay" name="btPay"> Go for Pay ...

Extracting information from an ENORMOUS Array

Let's start with my code snippet, featuring an array: var UserProfiles = [{ userProfileID: 1, firstName: 'Austin', lastName: 'Hunter', email: 'test', token: '', platform: 'android ...

Tips for postponing the execution of inline javascript

Main page <script> $.ajax({ type: 'GET', url: 'ajax.php', context: document.body, success: function(data) { $("#content").html(data); } }); </script> <div id="content"></div> Ajax ...

What is the process for adding an item to an object?

I currently have the following data in my state: fbPages:{'123':'Teste','142':'Teste2'} However, I am in need of a dynamic solution like the one below: async getFbPages(){ var fbPages = {} awa ...

Navigate to a separate file using an express route

Currently, I am a newcomer to working with Express and using the Backbone Boilerplate. During development, when requesting /assets/css/index.css, I would like to serve the file located at /public/dist/debug/index.css. Here is what I have attempted so far: ...

Preventing an event from bubbling up to its parent in a jQuery Ajax call: A step-by-step guide

I am working on a page that showcases a tree list using unordered lists. Each li element with children triggers an ajax call to fetch those children and display them as another ul/li combination, which is functioning correctly. However, the problem arise ...

Instructions for deleting a class from the body with jQuery while incorporating AngularJS

When using jQuery $(document).ready(function() { $("#pid1").removeClass("login_page"); }); HTML <body class="login_page" id="pid1" ng-app="myApp" ng-controller="myCtrl"> On the main page, a class is removed, but on the login page I want to ...

Updating the quantity of a product within a state in React allows for easy manipulation of that

My scenario involved attempting to reduce the quantity of a product object in the UI by clicking a button, but the quantity did not update as expected. What is the recommended course of action in situations like this? let product={ a:1,b:2,c:3}; For examp ...

What is the best way to retrieve a message from a resource file using JavaScript?

I have both English and Japanese resource files. When my website switches to Japanese language, I need the messages to display in Japanese just like they do in English. This will require dynamically displaying messages in JavaScript. Thank you. ...