|
One of my friends asked me how to dynamically include a reference to the JavaScript file into an html file. Sincerely to say, I didn't know what to answer. But no additional effort was needed to find the answer, it's easy. If you are familiar with JavaScript, then you can think of it yourself and you'll find the answer.
I wrote a function in JavaScript which makes all the work: dynamically creates object corresponding to the "<script>" tag, assigns it's "src" property a value of file name, and then adds this object to the current document. Have a look:
<script language="javascript" type="text/javascript"> function IncludeJS(file) { var scr = window.document.createElement("script"); scr.src = file; document.body.appendChild(scr); } </script>
All works fine. One more thing I would mention here: When invoking a method that is contained in dynamically referenced script file, always make a little more coding to ensure that no script errors will be thrown. For this purpose, my test button's "onclick" event checks, if the method that SHOULD be in the included file, exists. Look at this button tag:
<input type="button" value="Invoke Sample Method" onclick="if (window.SampleMethod) SampleMethod()" />
That's all about today's JavaScript.
|