JavaScript Intro
JavaScript provides the ability to add interactivity to a website, and help enrich the user experience. HTML provides a page with structure and CSS provides a page with appearance, JavaScript provide a page with behavior.
Generally speaking, the best place to reference JavaScript files is right before the closing </body>
tag so that the JavaScript file is loaded after all of the HTML has been parsed. However, at times, JavaScript is needed to help render HTML and determine it’s behavior, thus may be referenced within a documents head
.
Where is the leading http?
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="script.js"></script>
You may have noticed that there isn’t a leading http within Google CDN reference example above. The http has been omitted intentionally to allow for both http and https connections. When working locally, without the benefit of a web server, the leading http will need to be included to prevent attempting to locate the file on the systems local disk drive.
Document Ready
Before trigging any jQuery to traverse and manipulate a page it is best to wait until the DOM is finished loading. Fortunately jQuery has a ready event, .ready()
, which can be called when the HTML document is ready to be altered. By placing all of our other custom written jQuery inside of this function we can guarantee that it will not be executed until the page has loaded and the DOM is ready.
$(document).ready(function(event){
// jQuery code
});