0

I was testing and see if I can use javascript to load .js after the document is ready, and got this warning message from chrome:

"Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience."

My codes are like:

$(document).ready(function(){
    var s=$('<script src="test.js"></script>');
    $('body').append(s);
});

My questions are:

1) In this case, what is considered a "Synchronous XMLHttpRequest"? I think it is related to the loading of 'test.js', but if I change it to var s=$('<img src="image.png"></img>'); the warning message won't show.

2) If the .js file has to be loaded this way, what is the best practice?

*********** Editting ***********

The content of test.js is

console.log(document.getElementsByTagName('h1'))

There is a h1 in HTML.

shenkwen
  • 3,536
  • 5
  • 45
  • 85
  • http://stackoverflow.com/questions/950087/include-a-javascript-file-in-another-javascript-file – Raphael Rafatpanah Jul 06 '15 at 18:09
  • 4
    That is not a synchronous XMLHttpRequest. That JS file is probably making one. – SLaks Jul 06 '15 at 18:11
  • The content of test.js is just `console.log(document.getElementsByTagName('h1'))`, I'm editting this to the main thread. – shenkwen Jul 06 '15 at 18:19
  • Appending a script tag in document does not create XMLHttpRequest. Problem lies somewhere else. The error message must be accompanied by a line number and filename, can you check and post what is causing this error? – Salman A Jul 06 '15 at 18:29
  • it is this line in jQuery 2.1.4(http://code.jquery.com/jquery-2.1.4.min.js): `if (f.open(a.type, a.url, a.async, a.username, a.password), a.xhrFields)` – shenkwen Jul 06 '15 at 18:32

1 Answers1

0

I believe your problem is relating to async

In HTML5: async, defer, you can tell browser when to run your JavaScript code. There are 3 possibilities:

<script       src="myscript.js"></script>

<script async src="myscript.js"></script>

<script defer src="myscript.js"></script>
  1. Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.
  2. With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.
  3. With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. This is good.)

I found below answer: synchronous-xmlhttprequest-on-the-main-thread-is-deprecated

Using jQuery to append a script tag to the document will cause it to load the script with async:false and trigger this warning.

var script = $("<script></script>");
script.attr("src", player.basepath + "whatever.js");
$(document.body).append(script);

Not tested. Just for your information.

Community
  • 1
  • 1
SK.
  • 4,174
  • 4
  • 30
  • 48