I'm almost new to web developing and I'm facing to Javascript/jQuery. I would like to understand how a script is executed in an html page. I'm a C/Java programmer and references to these languages could help me. I understood that a script can be inserted in the header or at the end of the body if we want to execute it after the page is loaded. I know that a function can be called by a DOM event (I associate events to interrupt signals). What I would like to know is if a script like this:
<script type="text/javascript">
//<![CDATA[
var i=10;
if (i<5)
{
// some code
}
//]]>
</script>
in the body or in the head element is executed only once or is executed continuously. Does jQuery behave in the same way as Javascript? What about plugins? Do they live for all the time a page is shown (like a parallel thread) or are they event driven (they are called by clicking/resizing etc or using timers)? I know that is a very general question and that probably it cannot be explained in a few lines but some basic explanation and a link to some documentation would be very appreciated.
Thank you!
jQuery is just a library written in JavaScript that mainly simplifies DOM manipulation and working with AJAX requests. If you want to understand how JS works, forget about jQuery for a moment.
Regarding script execution: The browser parses the HTML and creates a DOM out of it. When the browser encounters a <script>
tag and its content, it creates a DOM element for it, adds it to the tree and executes the code. Then it continues parsing the next tag, which implies that the code is only executed once.
The reason for executing the script during parsing is that the script can already manipulate the HTML right away (using, e.g. document.write
(not good practice though)) and therefore change what the parser has to parse. Script execution can be deferred using the defer
attribute, until the document is fully parsed (I haven't seen the attribute very often in live code until now though).
All script
tags share the same scope, the global scope and the execution environment persists until you navigate away or reload the page. So, defining a variable in one script and accessing it in the other is perfectly valid and in fact is what you are doing when you include libraries like jQuery in your page.
<script>
var foo = 'bar';
</script>
<!-- other HTML code -->
<script>
alert(foo);
</script>
You might find the HTML documentation about script
s helpful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With