Load and execute javascript code SYNCHRONOUSLY Load and execute javascript code SYNCHRONOUSLY javascript javascript

Load and execute javascript code SYNCHRONOUSLY


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();


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);}


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.