What is the best way to synchronously load JSON in JavaScript?

I've encountered an issue while trying to develop an HTML5 game. My goal was to create a modular game by using a JSON file with different modules to load.

Here's the code snippet I attempted

var resources = {};

$.ajaxSetup({
  async: false
});

$.getJSON('res/gen/generators.json', function (data) {
  resources.generators = data;
});

for (let generator in resources.generators) {
  $.getScript("res/gen/" + resources.generators[generator].folder + "/script.js");
}

$.ajaxSetup({
  async: true
});

The content of the JSON file

{
  "memoryless": {
    "folder": "memoryless",
    "name": "Memoryless",
    "description": "Generates a piece with no regard to the previous history."
  }
}

However, I'm facing an error message stating "[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check ." I want to ensure that no other code runs until these scripts are loaded. Any suggestions on how to resolve this?

Answer №1

Struggling against the asynchronous nature of JavaScript may result in a less than pleasant development experience. Embrace and utilize asynchronicity to your advantage.

Let's delve into nesting promises and callbacks with the following code snippet:

var resources = {};

$.getJSON('res/gen/generators.json', function (data) {
  resources.generators = data;

  $.when(Object.keys(resources.generators).map(function(generator) { 
    return $.getScript("res/gen/" + resources.generators[generator].folder + "/script.js");
  }).then(function() {
    ...perform additional tasks
  })
});

Alternatively, consider utilizing async/await:

(async () => {
  var resources = {}
  resources.generators = (await $.getJSON('res/gen/generators.json')).data;

  for (let generator in resources.generators) {
    await $.getScript("res/gen/" + resources.generators[generator].folder + "/script.js");
  }
  ...perform additional tasks
})()

Another option is to forgo your custom module system in favor of standard JavaScript Modules:

import memoryless from "res/gen/memoryless/script.js"

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

Create a dynamic sitemap for a Laravel website that includes variables in the slugs

My Laravel-based website features URLs like this- xyz.com/search/{id}/{name} These URLs have two variables, allowing for multiple variations such as: xyz.com/search/1/katy xyz.com/search/2/john With potentially thousands of such URLs, I need to creat ...

Developing an Addon for Firefox using XUL and JavaScript

I am interested in creating a Firefox Addon that dynamically generates a button in the webpage's DOM when a specific page like www.google.com is loaded. This button, when clicked, will redirect to another page such as www.stackoverflow.com. It is imp ...

Customize URL based on selected button

My question may be a bit unclear, but I want to generate dynamic URLs that redirect users to specific pages based on the link clicked. For example: Parent page with links (a, b, c, x, y) User clicks on 'b' User is taken to a Node Page that play ...

Transmitting various pieces of information using AJAX

Is it possible to send both "credit_uri" and "address" strings in one AJAX request? Currently, only the second string is being sent. How can I include both in the data of the request? $.ajax({ url: '#{add_cards_path}', type: 'POST&apo ...

What is the most effective way to incorporate an Ajax partial page refresh in this specific code snippet?

I'm in the process of updating a specific section on my page. This particular section is enclosed in a division tag with a designated "class name". In order to keep things straightforward and avoid any confusion, I am seeking guidance on how to implem ...

Send a file from a form using Gatsby to getform.io using the axios library

I am facing an issue with my getform.io form where the file is not getting uploaded properly. The file appears as [] and the files tab remains empty. Upon checking the network tab, I noticed that my request payload includes {email: "[email protec ...

Prevent the use of harmful language by implementing jQuery or JavaScript

Is there a way for me to filter certain words (such as "sex") using regex, even when people use variations like "b a d", "b.a.d", or "b/a/d"? How can I prevent these kinds of words from getting through? I'm trying to filter more than just one word - ...

Is there a way to showcase my information on flash cards using JavaScript?

Currently, I am developing a full stack application that utilizes JavaScript on both the front and back end. This application allows users to create their own flashcards set. Upon clicking "View Cards," the data is fetched and the question-answer pair is d ...

AngularJS ng-repeat: displaying a list of filtered outcomes exclusively

I currently have a ng repeat that loops through a set of results. <a class="list-group-item" href="#trip/{{trip.id}}/overview" ng-repeat="trip in trips | filter:search | limitTo:-15"> Basically, as I enter more text into my input field, the list sh ...

VeeValidate fails to validate input fields in a form that is constantly changing

My goal is to create dynamic forms with validations using veeValidate in Vue.js. I am attempting to achieve this by storing an array of objects within the component's data. For instance: data(){ return{ inputs: [ { id: 1, lab ...

Managing the Response from an Ajax Call

Currently, I am in the process of developing a user registration form for my website and have implemented ajax to manage server-side processes. My main issue lies in effectively handling the response generated by my PHP code. The potential responses from t ...

How to determine if a radio button has been selected using Javascript?

I have come across scripts that address this issue, however they are only effective for a single radio button name. My case involves 5 different sets of radio buttons. I attempted to check if it is selected upon form submit. if(document.getElementById(&ap ...

When implementing AJAX functionality, the includeSelectAllOption feature does not seem to function properly

The select all option is not working in the second drop-down, but it works for the first dropdown where I fetch dropdown options from a database. In my second dropdown, I hardcoded the dropdown options. <?php include_once("connection.php"); $query="sel ...

What's the issue with this code not functioning correctly?

puts.php (JSON) { "image":[ { "name":'<div id="yes">Hi!</div>' } ] } process.php <HTML> <HEAD> <TITLE>Process</TITLE> <script type="text/javascript" s ...

Is it possible for me to reply to packets that are transmitted to a website?

I'm currently working on a Python program that sends a 'hello' packet to the server and I'm wondering if I can get the server to respond based on that. Here's the code snippet I'm using to send the packet: import requests hL = ...

Using CakePHP to transfer information from a view to a controller through AJAX

Recently delving into cakephp, I've been attempting to create a straightforward ajax request to dynamically modify a section of the screen. Although I've come across numerous examples online, I'm struggling to amalgamate them seamlessly! Upo ...

Is there an easy method for extracting URL parameters in AngularJS?

Hello, I'm new to Angular and coming from a background in PHP and ASP. In those languages, we typically read parameters like this: <html> <head> <script type="text/javascript"> var foo = <?php echo $_GET['foo&apo ...

Display the bash script results on an HTML webpage

My bash script fetches device status and packet loss information, slightly adjusted for privacy: #!/bin/bash TSTAMP=$(date +'%Y-%m-%d %H:%M') device1=`ping -c 1 100.1.0.2 | grep packet | awk '{ print $6 " " $7 " " $8 }'` device2=`pin ...

I just obtained the height measurement of a dynamic table - now I must transfer this height value to a different element

Recently, I encountered a situation where I needed to get the height of a dynamic table using code like this: var table = document.getElementById("test"); document.write(table.offsetHeight); However, the challenge arose when I realized that I also needed ...

Having trouble with jQuery div height expansion not functioning properly?

Having a bit of trouble with my jQuery. Trying to make a div element expand in height but can't seem to get it right. Here's the script I'm using: <script> $('.button').click(function(){ $('#footer_container').anim ...