Loading JavaScripts Dynamically

Sometimes to keep the pageweight down … we have split our scripts into fragments…These javascript fragments can be loaded as and when required ( on an event or on click of a  link or button etc.).

Loading Javascripts dynamically is simple and pretty straight forward  as below… 

<script type=“text/javascript”>
function loadNewScript(source){
  var s = document.createElement(’script’);
  s.setAttribute(‘type’,'text/javascript’);
  s.setAttribute(’src’, source);
  document.body.appendChild(s);
}
</script>

and you can have the following call link anywhere in the body , or you can have this script “onLoad” of the document itself…

<a href=“javascript:loadNewScript(‘myDynamicScript.js’);”>Load Dynamic Script</a>

or

<body onload=”loadNewScript(‘myDynamicScript.js’);”>


One Response to “Loading JavaScripts Dynamically”

Leave a Reply

 
NDK home | Expressing IT | Expressing Palate | Expressing Penmenship | Expressing Awe | Expressing Myself