Spread the word

Thursday, October 30, 2008

How to add link and script codes in the Head tag from the body section through JavaScript

Many times we need to add <script> or <link> tags for some selected pages of a website. In many websites we use Content Management Systems or some templates where we can’t add different headers to different pages. But in many pages we need some extra functionality through scripts and other codes which are used differently in different pages within that site. Sometimes we need to insert the scripts within the page body tag which is not at all Web Standards compliant. The scripts and links to css or JavaScript files should always be in the head tag.

So here is the process of inserting the scripts within the head tag without having access to individual headers. You can easily insert codes from your page body to page head section through JavaScript. Here is a sample code to do this:
<script type="text/javascript">
  var headID = document.getElementsByTagName("head")[0];       
  var cssNode = document.createElement('link');
  cssNode.type = 'text/css';
  cssNode.rel = 'stylesheet';
  cssNode.href = 'http://www.domain.com/styleNew.css';
  cssNode.media = 'screen';

This is an example how you can add a link to a CSS file in your head tag from your page body section for that particular page.

Explanation: Here we create a variable ‘headID’ and at the same time we assign it an element which has the tag ‘head’ and which is in the first position in the document from the top. Then we again create an element ‘cssNode’ which is a ‘link’ type element. Then we make the properties of the link element which are type, rel, href and media. Now when the total link element is created, it is appended within the head tag. This is how the link is put into the head tag from the page body.

In this similar manner you can easily add different codes or scripts into the head tag for specific pages. This being added into the head tag, is totally standards complaint and works absolutely fine.


Fiji Web Design said...

You can also use this to create JavaScript <script> tags. This allows you to import new JavaScript from a remote resource (even cross-domain).

Anonymous said...

Hi! this is the perfect solution that I was looking for. But when I tryed to implement it on my client's phpnuke site, it simple doesn't work.

Please I need your help and sorry about my English... my mail guitresan[a]gmail.com

Prasetya said...

Nice Post !

Anonymous said...

Hi, thank you for this!
Have you any idea how to close a script line when added like this?!
Some sites/browsers seem to need the full xhtml syntax...

Jay said...

Thanks, this worked perfectly.

Vrt said...

Hi, this not working in IE. It has problem with appendChild(). Some solution?

Post a Comment