PHP does not know JavaScript
PHP can not directly call a JavaScript function because PHP is interpreted on the server side.
PHP does not see a code there, it simply copies the character-by-character text and sends it to the user's browser.
The browser knows JavaScript
When the browser reads the data already received in HTML, it starts interpreting this HTML and assembles the elements on the screen.
When encountering a <script>
tag the browser stops what it is doing and executes what it has in that script.
Note that at this point the browser is running the script on the user's computer, while PHP (which may have already finished running) was running on the server.
Run code on page load
So, for every effect, the code quoted in the question will run in the browser exactly the moment the browser receives it from the server. An explicit call is not required.
<script language="javascript" type="text/javascript">
//todo código aqui será executado
</script>
Performing functions
However, in the case of having a declared function, the excerpt is interpreted and the function is created, but it is not invoked automatically:
<script language="javascript" type="text/javascript">
function f_mostra() {
alert("Entrei");
}
</script>
However, just add a call after the function declaration to execute it:
<script language="javascript" type="text/javascript">
function f_mostra() {
alert("Entrei");
}
f_mostra();
</script>
Or:
<script language="javascript" type="text/javascript">
function f_mostra() {
alert("Entrei");
}
</script>
<!-- ... -->
<script language="javascript" type="text/javascript">
f_mostra();
</script>
Waiting for the page to be ready
The problem is that it is not always desirable to run JavaScript while the page is loading, after all the browser may not have finished putting all the HTML in yet.
You can then capture the event that says if the page is fully loaded :
window.onload = function() {
//executado quando tudo na página está carregado
};
Everything I said above is not exactly true;)
There are techniques and technologies that actually allow PHP (or any other language) to execute a JavaScript function when the user is with an open page, without a new request.
Today with HTML 5, we have WebSockets technology that enables persistent communication between client (JavaScript) and server (PHP). However, I will not go into detail, as it is a more complex subject.