Load and execute javascript code SYNCHRONOUSLY
Is there a way to load and execute a javascript file in a synchronous way just like a synchronous XMLHttpRequest?
I'm currently using a sync XMLHttpRequest and then eval for this, but debugging that code is very difficult...
Thanks for your help!
Update
I tried this now:
test.html
<html>
<head>
<script type="text/javascript">
var s = document.createElement("script");
s.setAttribute("src","script.js");
document.head.appendChild(s);
console.log("done");
</script>
</head>
<body>
</body>
</html>
script.js
console.log("Hi");
Output: done Hi
So it was not executed synchronously. Any idea to make "Hi" appear first?
Update 2 Other example
test.html (code inside a script tag)
var s = document.createElement("script");
s.setAttribute("src","script.js");
document.head.appendChild(s);
SayHi();
script.js
function SayHi(){
console.log("hi");
}
Output: Uncaught ReferenceError: SayHi is not defined
Solution 1:
If you use this:
function loadScriptSync (src) {
var s = document.createElement('script');
s.src = src;
s.type = "text/javascript";
s.async = false; // <-- this is important
document.getElementsByTagName('head')[0].appendChild(s);
}
You can do what you want (although divided up in an additional script file)
test.html (code inside a script tag):
loadScriptSync("script.js");
loadScriptSync("sayhi.js"); // you have to put the invocation into another script file
script.js:
function SayHi() {
console.log("hi");
}
sayhi.js:
SayHi();
Solution 2:
All scripts which are loaded after DOM is ready are loaded asynchronously. The only reason for browser to load them synchronously is function write
which can output something. So you can use onload callback of the script element to achieve what you want.
var s = document.createElement("script");
s.setAttribute("src","script.js");
s.onload = function(){
console.log('Done');
}
document.head.appendChild(s);
Another way is to load js-file via XHR and set code inside the script element:
window.onload = function(){
var req = new XMLHttpRequest();
req.open('GET', "test.js", false);
req.onreadystatechange = function(){
if (req.readyState == 4) {
var s = document.createElement("script");
s.appendChild(document.createTextNode(req.responseText));
document.head.appendChild(s);
}
};
req.send(null);
}
Solution 3:
From a similar question ( https://stackoverflow.com/a/3292763/235179 ):
<script type="text/javascript">
document.write('<script type="text/javascript" src="other.js"><\/script>');
</script>
<script type="text/javascript">
functionFromOther();
</script>
Either the code called from the document.write
'd script needs to be in it's own <script>
or it needs to be in the window.onload()
event.