Connecting a script dynamically from a Javascript script itself is not difficult, here’s a complete example, here we load the script from a file named test.js, which is in the current folder:
var script = document.createElement ('script');
script.src = 'test.js'; //or the full URL of the file js
document.getElementsByTagName ('head')[0].appendChild (script);
alert('script loaded'); //for illustration purposes only, you can remove the line
Another thing is that the usefulness of this approach is questionable – for example, you cannot simply describe a function or a global variable in a test.js file and then use it in a plug-in script. Since there are no “pure classes” or namespaces in Javascript, programmers simply create an object and think of it as a namespace. You can see examples in the source code of the popular JQuery library.
Here’s a little example of our own.
The lib.js file contains the core of the system:
var lib = {
add : function (name, method) { lib[name] = method; }
};
The file functions.js is a “program module”, it describes the implementation of functions, in this listing there is only one function, in fact there can be any number of them.
function f1() { return 1; }
lib.add ( "f1", f1 );
The script.js file is an “implementation” and can use library functions:
var t=lib.f1();
alert (t);
It remains to load it all in the right order, here is the corresponding HTML document:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=Windows-1251" http-equiv="content-type">
<title>Тест</title>
</head>
<body>
<script type="text/javascript" src="lib.js"></script>
<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript" src="script.js"></script>
<noscript><p>I'm sorry, the application needs to be switched on in order to work Javascript</p></noscript>
</body>
</html>