0

Can anyone suggest where should I put my JavaScript and CSS code in an ASPX page? In the beginning or at the end? Does wrong placement of JavaScript and CSS affect the optimization of page?

4 Answers 4

2

Its better if you have both of them in separate files and then include them in your aspx page. This way it will enable you to use the same CSS and Javascript on multiple pages.

But if you are looking to use the CSS and Javascript in only a single page then You should put your css in head tag, You can put javascript between head tag or any where between html but best place to put javascript is between head tags. Its better to put js like jquery libraries file in head.

Sign up to request clarification or add additional context in comments.

3 Comments

Can i write a js function on head tag that depends on the file loaded at bottom of page? Example writing document.ready event in head tag and referring jQuery.js at bottom. Will it work?
@Murali, Try using $(window).load instead of document.ready to ensure your scripts executes after loading of your .js file is done.
separate css and java-script files means more server request. But the browser can cache these file main benefit.
1

Putting your CSS at the top of the page and JavaScript at the bottom of the page(before the closing body tag) is the best way when you want the CSS and Scripts in the same page.

You can have a read at this article(the stated points are explained in the middle sections)-

http://developer.yahoo.com/performance/rules.html

The reason why JavaScript should be at the bottom is that any page elements that you access in your JavaScript should be loaded first in the DOM. If you write them in the <head> section, it is likely that the JavaScript may fail to find the elements in the HTML and report errors or fail to execute.

Comments

1

I would suggest to

  1. put stylesheet calls to the top of the <HEAD> element and
  2. scripts at bottom of the page that is after </body> tag. (In some cases)

Becuase that will make your web pages load faster.

Note:

The second point will not always be true because in some cases you want your scripts to execute part of the content with the help of these scripts.

So YES, the wrong placement of javascript and css affect the optimization of page

Comments

0

I would like to add one point:

Scripts should be kept at bottom of the page, e.g. after </body> tag provided page loading is not dependent upon that script.

Note: Placing scripts at the bottom of the page improves display speed, as script compilation slows down the display.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.