Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Include JavaScript on a Public Facing Website?

Tags:

javascript

I am building a public facing website and I am using a lot of jQuery and jQueryUI. What I have noticed is that most site on internet that use jQuery and jQueryUI don't have code like this in their pages.

<script type="text/javascript">
  $(document).ready(function(){

    $("a").click(function(event){
      alert("Thanks for visiting!");
    });

    $( "input:submit" ).button();
  });
</script>

I know this is a simplistic example but most sites, for example SO have only one obfuscated js file included for all the pages. It doesn't even seem like they use $(document).ready anywhere. On my current site it seems like I would need to include a js file for each page. My question is how is it suppose to be done and is there a best practice on how to use/include javascript in a page?

like image 261
Lukasz Avatar asked Dec 09 '10 16:12

Lukasz


2 Answers

You wouldn't see the famous document.ready because most of the code is compressed usually into one big file for caching purposes. Just include your js at the end of the body like:

<script type="text/javascript" src="site.js"></script>

so this can be cached once and for all for every page.

like image 137
Ege Özcan Avatar answered Oct 11 '22 17:10

Ege Özcan


According to W3C you could put scripts almost anywhere: http://www.w3schools.com/js/js_whereto.asp

So where should you put them?

Ege is right to say that you should put them as far down the page as possible because it will enable the browser to load more in parallel up front before it gets to the 'blocking' scripts. See here for more detail: http://developer.yahoo.com/performance/rules.html#js_bottom

Also, it is nearly always a good idea to put your scripts (and CSS) into external files so the browser can cache them tus saving the user from having to download them with the page each time.

Personally, I always use a CDN for script frameworks such as jQuery and the like as they can deliver external resources quicker than you probably can. Also the likelyhood of the browser having already cached jQuery for another site from the same CDN is far more likely. More detail here: http://code.google.com/apis/libraries/devguide.html

Finally, there's nothing wrong with using $(document).ready, but just be aware that this could affect the site's responsiveness and its pros may not outweight its cons. Again, more detail here: http://encosia.com/2010/08/18/dont-let-jquerys-document-ready-slow-you-down/

Hope this helped.

like image 44
delimited Avatar answered Oct 11 '22 18:10

delimited