I'm creating an AJAX heavy web application and I'm curious on what people's thoughts are on adding style and script tags to the body of an HTML document.
I've been using the jquery.load() method to insert content on the fly. An example partial HTML page that could get loaded into the body element is this:
<script type="text/javascript">
$(function() {
// All required java script for the control goes here...
});
</script>
<style type="text/css">
/* All required styles for the inserted HTML go here */
</style>
<div id="some-control">
<!-- Required HTML markup is here. -->
</div>
Since this HTML is getting loaded into a DIV, we are ending up with script and style tags that are not in the head but in the body of an HTML document. I'm not sure if this is valid HTML? Is this a common approach to developing AJAX enabled web applications? Are there any drawbacks I should be aware of?
As far as Javascript is concerend, you can put it any where on the page provided that elements it will work upon are loaded before and it does not throw the error undefined
element. Famous Yahoo performance article and even Google (in terms of SEO) suggests to put javascript at the end of the page just before the </body>
tag.
If you can manage to put your script just before </body>
tag, that is considered good approach otherwise what you are doing now should be fine if everything is working properly for you.
I would actually disagree with Sarfraz and say that you should avoid using <script>
and <style>
tags in your page body as much as possible. The advantages of moving your JS to an external file are endless. The most obvious include:
<script>
tag to make a change. Having all your code centrally located and universal allows for ONE change and DONECSS share a similar story. Again, with caching and centralized storage, and reusability. It's even more important, however, for styles to match on a website. From a UI standpoint, you don't want your fonts changing from page-to-page and you don't want to edit 40 pages every time you want to add a new style.
As far as having the JS in the document because you are using AJAX loaded content, I suggest you look into .bind
and .live
. They let you attach handlers to existing and future instances of a DOMObject. For example:
$('.class').live('click', function(){
alert('I was clicked!');
});
This will apply to any object that existed at page load AND objects that are later created. The following code will NOT - it only applies to objects created on load:
$('.class').click(function(){
alert('I was clicked!');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With