Let’s say I have the following script
<script type="text/javascript">
$(function($, d) {
var custom = {
settings: { news: $('div.news') },
init: function() { this.settings.news.html('new'); }
}
}(jQuery, $(document)))
</script>
You can assume that the object has more functionality, but my question is where should I place it?
I know two approaches:
-
Place the script in the
<head>tag. That way I will have to make sure the object is called only after document.ready, so the settings jQuery objects ($('div.news')) won’t be empty. -
The second way is less semantically correct in my opinion, but I can give up the document.ready function: I can just “physically” place the script after the html.
What solution would you prefer and why? Thanks from advance!
Any script that doesn’t assist in rendering the layout of the page should be placed at the bottom of the body, preferrably as a reference to a script file (not the script itself). This allows the CSS + HTML to render the page visually, and then the JavaScript (or jQuery, in your case) is applied to the rendered elements.
It does not increase the performance of the page perse, but it does speed up the visual rendering, appearing to provide a faster experience for the end user.
See here for more details.