Как правильно задать последовательность выполнения скриптов?
sobes.tech AI
Answer from AI
The sequence of script execution on the client side is determined by their order in the HTML document, the use of async and defer attributes in the <script> tag, as well as dynamic script addition.
HTML order:
The browser executes scripts in the order they appear in the document (<head> or <body>), unless the async or defer attributes are used. HTML parsing is paused until each script is fully executed.
Attributes:
-
async: The script is loaded asynchronously in parallel with HTML parsing. As soon as the script is loaded, HTML parsing is paused, the script is executed, and then parsing resumes. The execution order ofasyncscripts is not guaranteed.<script async src="script1.js"></script> <script async src="script2.js"></script> -
defer: The script is loaded asynchronously in parallel with HTML parsing. The execution of the script is deferred until the entire HTML document has been parsed. Scripts withdeferare executed in the order they appear in the HTML.<script defer src="script1.js"></script> <script defer src="script2.js"></script>
Comparison:
| Attribute | Script loading | Script execution | Execution order | HTML parsing pause |
|---|---|---|---|---|
| None | Blocks HTML parsing | Immediately after loading | In HTML order | Yes |
async |
Loads asynchronously, does not block | As soon as loaded (may block parsing) | Not guaranteed | Yes (during execution) |
defer |
Loads asynchronously, does not block | After HTML parsing is complete (DOMContentLoaded) |
In HTML order | No |
Dynamic addition:
Scripts added to the DOM via JavaScript (document.createElement('script'), element.appendChild()) are loaded and executed asynchronously by default. For synchronous or ordered asynchronous loading, callback functions or promises can be used.
// Example of dynamic addition with guaranteed order
function loadScript(src, callback) {
const script = document.createElement('script');
script.src = src;
script.onload = callback; // Execute callback after script loads
document.head.appendChild(script);
}
loadScript('script1.js', () => {
loadScript('script2.js', () => {
console.log('Both scripts are loaded and executed in order.');
});
});