Loading JavaScript Files Dynamically

Wednesday, June 25, 2008

So, you want to load the javascript code on runtime, for example, you want a spesific javascript to be loaded depending on some user input. How to do that? You can always use the document.write to add a new <script> element to the page. But it's not recommended and it's not working with some browsers. The better approach is to use DOM. First, create a <script> element, set the attributes, then add this element to page's DOM. Here's the example code. Remember to put the element inside the <head> section.

<script language="JavaScript" type="text/javascript">
  var myjs = document.createElement("script");
  myjs.setAttribute("type", "text/javascript");
  myjs.setAttribute("language", "JavaScript");
  myjs.setAttribute("src", "myscript.js");
  document.getElementsByTagName("head")[0].appendChild(myjs);
</script>
In that example, the script will load external javascript file named myscript.js, all you have to do is define the trigger of the script. Javascript and DOM are maybe the most powerfull way to manipulate your pages. That's how I see it. But we will discuss about this opinion later. Hope this helps,

0 comments: