The order of javascript execution can be unexpected when initiating ajax calls from a local file to a web server

Tested on Safari 5 for Mac OS X and on Safari for iOS devices:

When loading Javascripts within an ajax response, they are executed in the wrong order if the ajax request is made from a local file to a remote server (such as in a phonegap application).

To better demonstrate this issue, I have created some demo scripts:

(You will need to save this file to your local disk to replicate the problem)

Does anyone know why this occurs and how to ensure the correct script execution order?

Answer №1

Is it necessary to make the calls in sequential order? Are you executing asynchronous server calls? If that's the case, it's common for async calls to complete in unpredictable order.

One possible solution is to follow your initial idea, or alternatively, make synchronous calls to the web server.

Answer №2

One potential resolution might involve sending an index along with your Ajax request, saving the response (including both script and index) in an array at the designated index, and then verifying if all Ajax calls have been completed by checking the length of the array. Once all calls are finished, loop through the array and add the scripts accordingly.

Answer №3

This issue is occurring because the <script> tags within the HTML fragment you are loading are not executed by the browser directly, but rather by jQuery. Essentially, jQuery needs to manually scan the fragment for these <script> tags and then insert them into the document after inserting the rest of the HTML fragment into the designated element. This process bypasses the normal sequential behavior of the browser.

(While in the end, the browser does execute the script tags, it is jQuery that controls the orchestration, leading to an asynchronous flow due to the nature of dynamically added <script> tags.)

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

Guide to configuring Ionic Auto Height Sheet modal in Vue 3

Trying to implement an Ionic Auto Height Sheet modal in a Vue 3 project (https://ionicframework.com/docs/api/modal#auto-height-sheet). Below is the code I have written. In ion-tab-button #3, I included id="open-modal". Underneath the ion-tab-but ...

Reset input fields while retaining placeholder text

Seeking advice on how to use this handy jQuery tool properly: $('.myDiv input').each(function () { $(this).val(""); }); Though it clears my form, I'm struggling to maintain the placeholders of the inputs. Any suggestions? C ...

What is the process for incorporating a personalized SVG icon into a fontawesome library stored locally (fontawesome-all.js)?

I am trying to incorporate a custom SVG icon into my local fontawesome library (fontawesome-all.js) that is stored in my project's assets folder. I followed the instructions given on https://fontawesome.com/get-started but I am struggling to understan ...

What is the best way to make a div element take up the entire page

Is there a method to enlarge one div container to cover the entire page, similar to a zoom effect, without displaying any other elements on the page, and then enable the user to return to the normal view by pressing escape or clicking outside of the div ...

Encountering a syntax/parse error while utilizing jQuery within Velocity code

<script type="text/javascript> (function($, win) { function myCustomInit () { var self = this; var options = { 'params' : "userId=" + userId; }; self.init = function() { self.initButtonAction(); }; ...

"What are the most effective methods for posting an article with an image without the need to refresh the page

Users can use a remote form to share articles, and when the submit button is clicked, an ajax request is sent and the result is appended to the articles list. I am looking to enhance the functionality by allowing users to add images to their articles. I h ...

Confirm the email address using the autocomplete feature in the field

I'm currently utilizing Material UI to design an autocomplete field with multiple inputs that gives users the option to either choose from existing email addresses or input their own. An example of what I'm trying to achieve can be seen here: ht ...

NetBeans is unable to analyze javascript files that are considered "large" (over 350 KB)

I have a significant JavaScript file (approximately 6 MB) that includes library API and documentation as shown below: /** * Function doc */ library.class.func=function(something){}; /** * Function 2 doc */ library.class.func2=function(something){}; ...

Discovering the magic of activating a JavaScript function on jQuery hover

I need to call a JavaScript function when hovering over an li element. var Divhtml='<div>hover</div>'; $('li a').hover(function(){ $(this).html(Divhtml); //I want to trigger hovercall(); wh ...

The deployed app on Heroku is showing a 304 status code with no JSON response

I've been working on a project using React, Express, and MongoDB. While everything works fine locally, I encountered an issue with GET requests after deploying the project on heroku.com. Instead of receiving the expected JSON response, I'm gett ...

JavaScript code that involves manipulating dates within a nested loop

I'm currently developing a booking system where the pricing varies based on seasons that recur annually. The overall functionality is working smoothly, however, I am encountering difficulties with handling the recurring seasons. I have implemented mom ...

Setting value in Angular's ng-repeat directive

Utilizing ng-repeat, I am creating a table with radio buttons. The main goal is to assign each radio button a value based on the position of the object in the original array (before any sorting takes place). However, using $index assigns the position in ...

Having trouble parsing the get request using supertest

When testing get requests to my mLab app using supertest, I noticed an issue with the response. The regular GET request from Postman returns this: {"_id":"5b169a9951573c50d9682d52","text":"First test note","title":"Test1"} However, the response received ...

Mastering Data Transmission: Sending and Receiving Various Data Types Between React and Flask

Looking to send both user image and user data together to create a user on the backend using Flask. Currently, I am sending it as parameters but would like to include everything in the body of a POST request in React. React: const newData = new FormData( ...

Ajax is invoked only one time

The system is set up to display a follow button and an unfollow button. Clicking the follow button should make the unfollow button appear, and vice versa. Currently, when you click "follow", the database updates and the follow button disappears while the ...

React-select allows for multiple selections within a component when the onChange function

I am currently utilizing react-select. Per the official documentation, it recommends using 'isMulti' to select more than one option. Below is the custom component that I have created. import React from 'react'; import { Form } from &ap ...

Extracting JavaScript content with Selenium using Python

I am currently facing a challenge of scraping JavaScript data from a website. Specifically, I am trying to extract the number of Followers from this particular website. Here is the code I have come up with so far: import os from selenium import webdriver ...

Cycle through matching elements for managing unique slick carousels

My experience with using slick carousel and custom pagination has been positive so far. However, I'm now faced with the challenge of incorporating multiple carousels on a single page. While I have come across solutions, implementing them alongside my ...

Ways to conceal text that is not wrapped in an HTML tag

<div class="padd10_m"> <a href="http://www.caviarandfriends.com/job_board/user-profile/admin/" class="grid_view_url_thing1">admin</a> <img src="http://www.caviarandfriends.com/job_board/wp-content/themes/PricerrTheme/images/flags/us.pn ...

Sending array data from the client-side JavaScript to the Spring MVC controller via AJAX

Is there a way to send an array from JavaScript in a web browser to a Spring MVC controller using AJAX? Here's the JavaScript code I have: var a = []; a[0] = 1; a[1] = 2; a[2] = 3; // Is it possible to send multiple arrays as well? $.ajax({ typ ...