Page 1 of 1

calling js file through java script

Posted: Thu Dec 10, 2009 3:48 am
by myasirm
<input type="button" name="Btn3" value="Clear" onclick="clearForms()"/>

hi guys i want to call a java script page which contain complete java script code in php by clicking on button i used code like this but it is not working so how can i do this

<script LANGUAGE="JavaScript">
function clearForms()
{
src="clearform.js"
}
</script>

Re: calling js file through java script

Posted: Thu Dec 10, 2009 12:03 pm
by kaszu
As I understood you want to load a script when user clicks a button. There are several ways how to do it:
1) Insert <script> tag into the document (using DOM methods)
2) Load using XMLHttpRequest object (AJAX)
3) some other methods which in my opinion are not worth considering.

1) +easy to do - blocks browser until script is loaded and executed
2) +loads asynchronously, so it doesn't blocks browser (except when executing loaded JS) - more code to write

Here is untested example of 1)

Code: Select all

function loadScript (src) {
  var node = document.createElement('script');
  node.setAttribute("type","text/javascript")
  node.setAttribute("src", src);
 
  var head = document.getElementsByTagName('HEAD')[0];
  head.appendChild(node);
}
I hope loading external JS file to clear form is an example (not a good one), not actual place where it will be used :?

Google "dynamically load extenal javscript file"