Load and execute javascript code SYNCHRONOUSLY

Van Coding picture Van Coding · May 20, 2011 · Viewed 61.9k times · Source

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

Answer

heinob picture heinob · Feb 4, 2014

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