What is a script?¶
In the context of this course, a script is a JavaScript program which runs inside the user's web browser along with the HTML and CSS. Scripts get included in the page using the <script> HTML tag:
<script src="/path/to/script.js" type="text/javascript"></script>
The type attribute tells the browser that this script is using the JavaScript language and the src attribute is a path telling the browser where to load the script from. This script must be available on the web server just like an HTML document or an image file. In Rails applications, the convention is for JavaScript files to be places in the public/javascripts directory. Rails has a helper method called javascript_include_tag which will use this directory as default:
<%= javascript_include_tag "application" %>
The above gets translated to
<script type="text/javascript" src="/javascripts/application.js"></script>
when Rails sends the HTML to the web browser, which loads the application.js file and executes it. The <script> tag usually occurs in one or two places inside the HTML document. The first alternative is to put it in the <head> tag:
<html>
<head>
<title>Book club</title>
<script src="/javascripts/application.js"></script></script>
</head>
<body>
Page contents..
</body>
</html>
This can be a little tricky because when the browser gets to the script, it loads and executes it before the rest of the page has been loaded. A more convenient place to put the tag is right before the closing of the <body> tag:
<html>
<head>
<title>Book club</title>
</head>
<body>
Page contents..
<script src="/javascripts/application.js"></script></script>
</body>
</html>
This way, when the browser executes your script, you have access to the page's elements right away without having to tell your script to wait for the browser to tell you when it's done.
