Is it possible to include javascript files which contain parts of JavaScript script? I have quite a few JavaScript pages and they all use a few functions which are duplicated for each JavaScript file.
Thank you,
Kasia
Is it possible to include javascript files which contain parts of JavaScript script? I have quite a few JavaScript pages and they all use a few functions which are duplicated for each JavaScript file.
Thank you,
Kasia
Something like http://javascript.about.com/library/bladdjs.htm perhaps?
You can also just put the common functions in their own file and just make sure that file gets loaded before the others.
<script src=“common.js”></script>
<script src=“script that depends on the functions in common.js”></script>
Thank you for such quick replies.
So… there is no way to just add ad script into a function?
Something like this:
<?xml version=“1.0” encoding=“utf-8”?>
<html xmlns=“http://www.w3.org/1999/xhtml”>
<head>
<script>
function addJavascript(jsname,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement(‘script’);
s.setAttribute(‘type’,‘text/javascript’);
s.setAttribute(‘src’,jsname);
th.appendChild(s);
}
</script>
<script src=“includeJS.js”></script>
</head>
<body>
<input type=“submit” value=“scarry” onclick=“scream();”>
</body>
</html>
function scream() {
/*
* some code here
*/
addJavascript('extra.js','head');
/*
* some code here
*/
}
alert(‘aaaaaaaaaaah!’);
Try this, from Adding Javascript from Javascript
function addJavascript(jsname,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}
Usage:
addJavascript('newExternal.js','body');
addJavascript('newExternal2.js','head');
While you could write a function that would block execution and execute the js in the file before the function returns(ajax in synchronous mode + eval), this is a really bad thing to do. You would lock the browser up, and it’s just plain silly. It’s like trying to use a file in place of a function. Why not write a function?