1

AFAI read and glance at other questions, what appears in a HTML document, the lines executed in order. I think same thing is applied to a Javascript file. I expect in the following code, first background is painted as yellow then immediately get readyyyy message, but total opposite case happens. alert() runs firstly then page is yellow. Why?

js code,

$('body').css("background", "yellow");

function f() {
    alert("readyyyy");
}

$(f()); // same as $(document).ready(…)

html code,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<p>Testing...</p>

<script src="jquery.js"></script>
<script src="Test.js"></script>
</body>
</html>
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
concurrencyboy
  • 351
  • 1
  • 11
  • 1
    @MisterJojo no it doesn't...it is more about how callbacks work and happens to be using jQuery – charlietfl Jul 22 '19 at 21:15
  • Related dupe: https://stackoverflow.com/questions/7137401/why-is-the-method-executed-immediately-when-i-use-settimeout – Taplar Jul 22 '19 at 21:16

1 Answers1

4

The statement

$(f())

means, "Call the function f and pass its return value to the function $". It is distinctly different from

$(f)

which means "Call the function $ passing a reference to the function f".

The fact that the page turns yellow after the alert has to do with the way that browsers try to optimize page redraws. Your JavaScript code changes the page style, but because nothing else in your code relies on inspecting the page style, the redraw is deferred until the JavaScript finishes (which is after the alert() returns).

Pointy
  • 405,095
  • 59
  • 585
  • 614