0

Working on cleaning up my errors and depreciated web-pages,
I've run into this Warning Message:

jquery-3.4.1.js:9725
[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
For more help, check https://xhr.spec.whatwg.org/.

I want to properly handle the JavaScript right:

  1. Keep the scripts and links in a self-contained area, i.e.
  2. Run after the page loads


But I don't know how to:

  1. Convert from inline JS references to JS-file
  2. What the internal JS format should look like



I've been using:

<head>

    <script>$(document).ready(function () { $('<script/>', { type: 'text/javascript', src: 'assets/js/set-background.js' }).appendTo('head'); }); </script>

</head>

With the JS-file:


...
var body = document.getElementsByTagName("body")[0];
body.className += " change-" + idx;
...

The warning doesn't happen if the script is:


<body>
    ...
    <script src="assets/js/set-background.js"></script>
    ...
</body>



And tried,

<head>

    <script>$(function(){'assets/js/set-background.js'}) </script>

</head>
<head>

    <script type="text/javascript" src="assets/js/set-background.js"></script>

</head>
<body class="container" onload="assets/js/set-background.js">



I've seen other developers discussions:

  1. javascript - How to run a function when the page is loaded? - Stack Overflow
  2. Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it - Stack Overflow
  3. javascript - $(document).ready equivalent without jQuery - Stack Overflow
  4. How to run a function in jquery - Stack Overflow


And I've also been reading:

  1. onload Event
  2. .load() | jQuery API Documentation

1 Answers1

2

This warning isn't related to page load. The problem is that somewhere you used an XMLHttpRequest with 'async' parameter false.

This isn't good, because of the JS event loop behavior (single thread), so if the download of requested data takes longer time, the page completely freezes: no clicks, scrolling, other JS functions, nothing!

To solve the issue, you have to use asynchronous XMLHttpRequest, or the Web Workers.

FZs
  • 11,931
  • 11
  • 28
  • 41
  • Okay, so how do I find the XMLHttpRequest? The warning didn't happen until I tried to reformat the code, and I'm unfamiliar with finding where implicit async parameters might be. –  Jun 16 '19 at 18:00
  • @zach Search for something like: `xhr=new XMLHttpRequest(); xhr.open(/*something*/,/*something*/,false)`. And you can't create a linebreak in a comment ;) – FZs Jun 16 '19 at 18:03
  • 1
    @zach Or if you're using jQuery it could be `$.ajax` – ADyson Jun 16 '19 at 18:11