In a HTML file, I have the following scripts:
<head>
<script src="/script1.js" defer></script>
<script src="/script2.js" defer></script>
</head>
In script1, I am loading another HTML file:
(async function() {
await fetch("./header.html")
.then(response => { return response.text() })
.then(data => { document.getElementById("header").innerHTML = data; });
})()
The code in script2 uses the elements from header.html which is being loaded by script1. With the current codes, script2 doesn't wait for header.html to be completely fetched.
A proof of this is that I have added console.log("1") after the fetch of script1, and added console.log("2") at the beginning of script2. Even though in the HTML file, I am calling script1 then script2, but console.log('2') appears before console.log('1')
Thus causing script2 to read some null elements (which have not been rendered yet). I am trying to ensure that script1 finishes executing (thus the fetch operation finishes) before running script2. How should I do this?
thenof script1. Or at least call the script2 function in the promise of script1.script2simply doesdocument.getElementById("some element in header.html").style.display = block, but it generates an error of element undefined.deferattribute are added to a list of scripts to be executed once the document they are part of has completed loading. Whether they are executed in order is up to the parser. See this answer to a similar question; basically, once you usedefer, you've given up control on execution order.