Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an Javascript script has been loaded Asynchronously (Async) or async attribute is present?

I would like know if there exists a handy way to check if an script (on execution) has been loaded asynchronously.

E.g. the script tag:

<script async type="text/javascript" src="js/async.js"></script>

the script async.js:

if (_condition_to_check_if_this_has_been_loaded_async) { console.log("async: true") }
like image 782
Angel Humberto Vargas Avatar asked Jul 14 '16 09:07

Angel Humberto Vargas


People also ask

What is asynchronous JavaScript loading?

We can load our scripts in parallel while the page is still being loaded. This is called asynchronous loading. Once the scripts are loaded, they will call define which notifies RequireJS that the scripts are indeed loaded and executed. RequireJS will then call your main function and pass in the initialized modules.

What is async attribute in script tag?

The async attribute is a boolean attribute. When present, it specifies that the script will be executed asynchronously as soon as it is available. Note: The async attribute is only for external scripts (and should only be used if the src attribute is present).

Is script tag async by default?

Dynamic scripts behave as “async” by default. This can be changed if we explicitly set script. async=false . Then scripts will be executed in the document order, just like defer .


1 Answers

Unless you want IE compatibility, the correct answer to this problem is using the little-known but widely supported document.currentScript property.

This property returns the HTMLScriptElement of the script currently being executed (or nothing if the script isn't in a tag/is a callback or similar), which tells you if it has the async/defer attributes, among other things.

The MDN example even cites this exact use-case:

if (document.currentScript.async) {
  console.log("Executing asynchronously");
} else {
  console.log("Executing synchronously");
}
like image 72
GregRos Avatar answered Oct 05 '22 22:10

GregRos