Reputation: 939
2 Questions:
1) How Do You Know How To Initialize A Script? Is the code always in a certain spot in the js file, do you have to create the initializing code from scratch, etc?
2) Why don't you have to "activate"/initialize the jQuery script? The other scripts I'm using required activating, so why is it that jQuery.js doesn't require an internal script to get it going?
Just trying to wrap my head around the concept, thanks in advance!
Upvotes: 0
Views: 3417
Reputation: 909
Kolban answers the question, but with regards to your "other scripts" specifically, this is likely because these scripts operate on certain elements. However, you need to explicitly tell the script which elements you want it to operate on. This usually happens like this:
$(document).ready(function () {
$('#myElement').scriptName();
}
This tells your script that it can operate on the element with the ID myElement
. If this "initialisation" didn't exist, the script could cause unintended side effects by modifying things you did not want it to modify.
Upvotes: 1
Reputation: 15266
In a web page, JavaScript is loaded and executed via the HTML tags of:
<script src="scriptFile"></script>
or inline with
<script>
... code here ...
</script>
In both/either cases, the JavaScript loaded/found is executed immediately from the top of the source all the way to the bottom in the order it is found.
There is no "initialization" of JavaScript as might be found in, say, Java or C. There is no equivalent of a main() function as in:
class X {
public static main(String args[]) {
....
}
}
In JavaScript code just starts "executing" from the top.
It is not uncommon to see JavaScript code begin with a wait for the DOM to be fully loaded and prepared. For example a script that starts:
$(function() {
// ... code here ...
});
should be read as execute the function called "$" and pass it an annonymous function that should be run when the DOM has loaded. All these symbols, curly braces, brackets and such can be confusing but the best way to comprehend them is to still realize that all code runs top to bottom ... it just may not run immediately. For example:
var x = function() {
// ... some code ...
};
x();
Even though there may be tons of code inside the function definition, it does not run until the call to the function is made. In JavaScript separate code definitions from code execution.
See also this related Q&A:
main() function in JavaScript?
Upvotes: 3