Style information should be at the top, javascript at the bottom

The reason for having style information on top and javascript at the bottom has nothing to do with wordpress but everything to do with the way browsers are rendering the HTML page and the resulting user experience.

The browser tries to show activity as early as possible, and starts to draw the page almost immediately after the page was loaded. The drawing is based on the styling information available at the the time the element is being drawn. If a style information is read after the drawing process has started, the browser has to find all of the elements which might be affected by the new style and redraw them. The best thing to do is to give the style information a head start, and put it as close to the top of the page.

In terms of the wordpress plugin API it means that style information should be inserted at the wp_hook

function style() {
  echo " <style>p {color:red}</style>";
}

add_action('wp_head','style');

Javascript code may alter the structure of the page while it is being loaded (with the document.write function for example), but since the changes can have a bigger impact, the browser actually stop everything it does while a javascript code is being parsed and executed. If this happens while the page content is being rendered, for the user it feels like the page is loading slower. When the javascript is at the bottom of the file, it still takes the same amount of time for the page to load and the rendering to be completed, but since the page is rendered earlier the user feels as if the page was loaded faster, even if the progress indicator on the browser’s status bar had not reached its “complete” status.

In terms of the wordpress plugin API it means that javascript should be inserted at the wp_footer

function js() {
  echo " <script>var author="mark";</script>";
}

add_action('wp_footer','js');

Based on information from yslow related articles.

Leave a Reply