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

Restrict printing loops within the designated division layer

Is there a way to limit the number of rows displayed horizontally when using foreach? I only want to display 7 rows. Can this be achieved with CSS or pagination? Here is an image illustrating the issue: https://i.sstatic.net/yJx3N.png Currently, it print ...

Making changes to HTML on a webpage using jQuery's AJAX with synchronous requests

Seeking assistance to resolve an issue, I am currently stuck and have invested a significant amount of time. The situation at hand involves submitting a form using the traditional post method. However, prior to submitting the form, I am utilizing the jQue ...

Transforming the output from a processor into an array structure

Being a newcomer in the field of development, I have a question about how to retrieve data based on my requirements and what is considered the best practice? This is the structure of my design: JavaScript (Ajax call) >> ashx handler (Access databa ...

Update the CSS of a different element when hovering

Hello to all the jQuery developers out there! I have a question that's fairly simple. I'm trying to change a CSS attribute for an element when I hover over a different element on the page. I've created a fiddle for you to review, and I&apos ...

Is it feasible to use a component in a recursively manner?

Following a two-hour search for a solution, I decided to reach out to experts as I suspected the answer might be simpler than expected. The project in question is an Angular7 one. In my goals component, I aim to include a "goal" with a button labeled "+". ...

Ensuring Proper Alignment of Headers in CSS

I'm struggling to align my header correctly. Despite getting close in Internet Explorer, it looks terrible in Firefox with the code below. I've scoured forums for solutions but the more I try to fix it, the worse it looks. All I want is for heade ...

Easy steps to automatically disable a checkbox once the expiration date has been reached

I have this PHP code that retrieves values from my database. I want to prevent users from selecting or modifying items with expired dates. Could you assist me with this? The code below currently displays 'Expired' and 'Not Expired' on ...

CSS code for a fixed fullscreen menu with scrolling

I have implemented a full-screen menu that covers the entire screen, excluding the header and menu tab bar. You can view it here: https://i.stack.imgur.com/h5cQa.png On smaller screens, the entire menu cannot be displayed at once, as shown here: https://i. ...

Encountered an error: "Unexpected token < in JSON at position 4" while trying to fetch a link using Ajax

Apologies in advance for any language barriers, I'm using Google Apps Script to work on a task involving fetching JSON data from an AJAX link. However, I occasionally encounter the error message: Unexpected token < in JSON at position 4 The issue ...

What steps do I need to take to integrate my RASA assistant into my personal website?

Deploying my rasa chatbot on my live website is my next step. While Rasa worked smoothly on my localhost server, as a newcomer to web development, I found the official guide provided by RASA in the link below a bit challenging to comprehend: The RASA guid ...

Tokenizing with jQuery UI

I have been following a tutorial that utilizes jQuery UI to generate Facebook tokens, as shown in this link: However, I am facing an issue where I need to pass two values through JSON: the ID and the NAME. The server-side script is structured as follows: ...

Having trouble establishing a connection between MongoDB and a Node.js Express server on my local machine

While attempting to establish a connection between mongoDB and nodejs express using the post method, I added a logger that should display a message confirming that the database is connected once nodejs listens to mongoDB. However, I encountered an issue wh ...

What is the method for assigning a value to a Material UI text field?

Trying to create an autocomplete search feature using EsriGeocode and Material UI. The form includes Street name, City, State, and Zip code fields. Currently facing an issue where the Street name text field displays the entire address instead of just the s ...

Trouble with browser autocomplete/saved form during ajax requests

Searching for information on browser autocomplete and form saving can be tricky, especially when trying to find solutions related to custom autocomplete with ajax. Many developers are interested in customizing autocomplete features for various reasons such ...

Converting a LovelySoup AJAX table into JSON Format

Struggling to extract data from a table on a webpage that requires an AJAX call to reveal the information. Unfortunately, upon running my code, I encountered the following error: AttributeError: 'NoneType' object has no attribute 'find_all&a ...

The picture won't stay within the confines of the container

As I work on my fitness site, I wanted to incorporate a sponsor section. While exploring some code that matched the style of my website, I discovered this snippet below. However, being new to CSS, I struggled with fixing it to ensure that the images fit ...

Utilizing PHP for Interactive JavaScript Modals

Encountering an issue with my JavaScript. The modal initially functions correctly, but upon clicking it for the second time, two modals appear - one from the previous click and another new one. The stacking of modals continues each time the button is cli ...

Tips for incorporating a return statement within a network request function that is already returning information pertaining to the request

Is there a way to retrieve the data extracted from within newReq.on('response', (response) => {? var request = require('request'); const cheerio = require('cheerio'); const { app, net, BrowserWindow } = require('elect ...

Chrome is throwing a syntax error with an unexpected token in jQuery replaceWith

jQuery('div#top').replaceWith('<div id="top"> </div>') When I try to replace the entire content of the top div using jQuery, Chrome gives me an error: "Uncaught SyntaxError: Unexpected token" on the first line. I'm no ...

Using ng-selected directive along with ng-repeat in a select dropdown

Apologies for asking once more. I am having trouble setting a default value for a select element. Here is the code that I have been using: Plnkr I am unable to use ng-options in this particular scenario. Your assistance without utilizing ng-options would ...