Monday, May 2, 2011

Attach Java Script or CSS files dynamically using Java Script

If there is a need to dynamically load JS or CSS file then the following code is useful. just copy the below function in to a Java Script file and where ever the attachment is needed then call the function with the attributes as specified in the examples..

Function:

function dynamicload(filename, filetype)

{

if (filetype=="js") { //if filename is a JavaScript file

           var fileref=document.createElement('script')

           fileref.setAttribute("type","text/javascript")

           fileref.setAttribute("src", filename)

}

else if (filetype=="css") { //if filename is a CSS file

                    var fileref=document.createElement("link")

          fileref.setAttribute("rel", "stylesheet")

         fileref.setAttribute("type", "text/css")

         fileref.setAttribute("href", filename)

}

if (typeof fileref!="undefined")

        document.getElementsByTagName("head")[0].appendChild(fileref)

}

 

Example:

dynamicload("myscript.js", "js") //dynamically load to add .js file
dynamicload("mystyle.css", "css") //dynamically load to add .css file

No comments:

Post a Comment