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") }
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.
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).
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 .
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With