What happens when dynamically loaded static resources are loaded?

Currently, I am dynamically injecting HTML into a page using JQuery AJAX. The injected HTML contains script and link tags for JS and CSS files respectively. The issue I am facing is that my initPage() function runs before the script containing its definition has finished loading.

Below is an example of the HTML received from the AJAX call:

<script type='text/javascript' src='//domain.com/js/fillip.js'></script>
<script type='text/javascript' src='//domain.com/js/fillip2.js'></script>
<link href='//domain.com/css/fillip.css' rel='stylesheet'>

<iframe src='//domain.com/mypage'></iframe>
<script type='text/javascript'>
    $(function(){
        initPage();
    });
</script>

I am looking for a solution to execute additional JavaScript only after all scripts have been loaded, with the flexibility to handle varying numbers of required script and CSS file dependencies. Bonus points if the solution can also accommodate waiting for CSS files to load.

How can I ensure all necessary dynamic JS/CSS files are loaded before proceeding with the rest of my JavaScript code?

Answer №1

Scripts defined in the 'head' section of a document are processed in the order they are listed.

If you have a function call to init at the end of your document, enclose it like this:

$(document).ready(function() {
  initPage();
}

Another method is to load scripts sequentially by adding them one by one to the document using a control mechanism.

function loadMyJavaScript(jsPath, cb) {
  var loaded = false;

  // Create script element and add it to document head
  var script = document.createElement('script');

  script.onload = successHandler;
  script.error  = errorHandler;
  script.onreadystatechange = stateHandler;

  script.src = path;
  document.getElementsByTagName("head")[0].appendChild(jsScript);

  function successHandler() {
      if ( false == loaded ) {
           loaded = true;
           cb(path, "success"); 
      }
  }

  function errorHandler() {
      if ( false == loaded ) {
          loaded = true;
          cb(path, "error");
      }
  }

  function stateHandler() {
      var status;
      if ( false == loaded ) {
         status = script.readyState;
         if ( status === "complete" ) {
            successHandler();
         }
      }
  }
}

You can then call this function and assign a callback as shown below:

loadMyJavaScript("http path of the script", function(path, status) {
     if ( status == "success") {
        Load another script or call initPage();
    }

});

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

Creating a cascading layout with React Material-UI GridList

Can the React Material-UI library's GridList component be used in a layout similar to Pinterest's cascading style? I have utilized Material-UI Card components as children for the GridList: const cards = props.items.map((item) => <Card ...

Changing the color of the timePicker clock in material-ui: a step-by-step guide

I have been attempting to update the color of the time clock in my timeInput component (material-ui-time-picker) for material-ui, but unfortunately, it is not reflecting the change. Here is the code I am using: <TimeInput style ={heure} ...

Creating a clickable link that dynamically updates based on the span and id values, and opens in a new browser tab

I am attempting to create a clickable URL that opens in a new window. The URL is being displayed and updated on my HTML page in the following manner: Python Code: def data_cb(): return jsonify(waiting=await_take_pic()) Javascript Code: jQuery(d ...

The incorporation of zoom disrupts the smooth scrolling capability of the menu

My landing page has a menu that scrolls users to the selected section. However, my client prefers the page at a 90% zoom level. To accommodate this request, I added the following line of code: body { zoom:90%; } Unfortunately, when I click on a menu o ...

Tips for Validating a Strongly Typed View in MVC3 without Using a Model

I'm facing a roadblock in my project. The project consists of 3 layers: Data access using ado.net data model. A WCF service that retrieves data from the data access ado.net data model and sends a serialized class. An MVC web application that connec ...

The float right attribute doesn't stay contained within the box; instead, it drifts outside the box

I've been struggling to keep this box fixed at the top of the browser, but I'm facing an issue with the positioning on the right side. I can't seem to figure out how to solve it, so I'm reaching out for some help. #StickyBar #RightSide ...

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

What is the procedure for invoking a function when the edit icon is clicked in an Angular application

My current Angular version: Angular CLI: 9.0.0-rc.7 I am currently using ag-grid in my project and I encountered an issue when trying to edit a record. I have a function assigned to the edit icon, but it is giving me an error. Error message: Uncaught Re ...

What is the best way to convert this JavaScript iteration function into jQuery?

I recently encountered an issue with my JavaScript function that returns a list of elements with the class ".youtube", loops through them, and calls another function. The JavaScript logic is flawless, but I wanted to convert it into jQuery for better reada ...

Guide to triggering a change event on a react-number-format component

I am attempting to trigger a change event in order to modify the value of a react-number-format component within my component. During testing, I encounter a TypeError: value.replace is not a function error on the simulate('change', event) method ...

The success callback in JQuery Ajax does not function properly when constructing an array of Ajax calls

I am facing a challenge in building an array of custom objects by resolving promises from an array created based on another array. Consider having an array of letters = ['a', 'b', 'c']. I then map this array to make Ajax call ...

What is the proper method for effectively employing destructuring?

I'm trying to figure out how to properly return state with a fetched array using the spread operator. Here is my reducer code snippet: function themes(state = [], actions){ switch(actions.type){ case FETCH_THEMES_SUCCESSFULLY: const { th ...

Formatting issue with selecting checkboxes in Primefaces DataTable filter menu

I decided to replicate the Primeface showcase for filters on my Local JBoss installation by referring to the link provided below: http://www.primefaces.org/showcase/ui/data/datatable/filter.xhtml. However, I encountered an issue where my selectCheckboxMenu ...

Emphasize a passage by clicking on a different section of text

Seeking Assistance I am currently customizing this template which incorporates the MixItUp plugin. My query pertains to highlighting the "filter tab" upon clicking on the corresponding text when hovering over each image, a task I find challenging as a new ...

There seems to be an issue with configuring placeholders in Tailwind CSS

After deciding to switch to using only tailwind CSS, I noticed that on a particular page there were inputs with transitions but no icon on the inner left side. Adjusting the colors and position of the placeholder helped prevent collisions between the icon ...

Inaccurate AJAX response mentioned

For populating text boxes from a database, I am using an onChange event. Although the code runs, the response I get is incorrect. The code I am using can be found below: index.php <?php $servername = "localhost"; $username = "root"; $password = ""; $ ...

Tips for adjusting the initial scale to ensure your mobile website fits perfectly on the screen

I'm trying to figure out the best way to adjust the 'initial-scale' so that my website's width fits perfectly on any device screen when first loaded. Check out my website here: While it looks fine on regular browsers, I had some issue ...

Is it possible to include parameters in an HTML GET request with Electron.Net?

I have successfully implemented a function in an Angular component within an Electron application using HttpClient: var auth = "Bearer" + "abdedede"; let header = new HttpHeaders({ "Content-Type": 'application/json&a ...

Encountering an unexpected token ';' in a random generator while attempting to utilize an if-else statement for determining DOM manipulation

After dabbling in programming on and off for a few years, I've finally decided to dive deep with some simple personal projects. One of the tasks I'm working on is creating a randomizer for a pen and paper RPG, where it samples from an array at ra ...

Prepare the writing area for input

My inputs have validation indicators, such as a green tick or red cross, placed at the very right of the input (inside the input). Is there a way to specify the writing space inside an input without restricting the number of characters that can be enter ...