dominik
dominik

Reputation: 2761

JavaScript - order of execution of <script> tags

As stated in this SO question and many other similar, the order of execution of <script>s on the page should be the same as the order in which these tags are defined in the html document.

I created a simple Java (server side) test app that allows to execute a request and wait specified period of time before returning a response (relevant code snippet at the bottom of this question). It has a simple API:

http://localhost:8080/latency?time=XXX&response=YYY

Example request that will return console.log('done') after one second (1000ms):

http://localhost:8080/latency?time=1000&response=console.log(%27done%27)

Next I created a simple index.html page (served by nginx):

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>test order</title>
    </head>
    <body>
        <script type="text/javascript" async=false src="http://localhost:8080/latency?time=1000&amp;response=console.log(%27done1%27)"></script>
        <script type="text/javascript" async=false src="http://localhost:8080/latency?time=100&amp;response=console.log(%27done2%27)"></script>
        <script type="text/javascript" async=false src="http://localhost:8080/latency?time=10&amp;response=console.log(%27done3%27)"></script>
        <script>console.log('static script without "src" attr');</script>
    </body>
</html>

According to everything I read so far I expected the order of console output to be:

done1
done2
done3
static script without "src" attr

This is what I got (Firefox 51 dev console):

latency requests 1

latency requests 2

This is just the opposite order of what I expected to get. Am I missing something? Is there a way to execute these scripts in the desired order (i.e. in the order they are defined in HTML)?

As a reference, the Java part on a server side:

private String latency(HttpServletRequest request) {

    long millis = Long.parseLong(request.getParameter("time"));
    String response = request.getParameter("response");

    try {
        Thread.sleep(millis);
        return (response != null) ? response : "";
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

Upvotes: 1

Views: 90

Answers (1)

Marat Tanalin
Marat Tanalin

Reputation: 14123

async is a boolean attribute. Its value does not matter. Remove the attribute.

Upvotes: 5

Related Questions