...

View Full Version : vary call parameter



rps
11-17-2010, 02:09 PM
When calling a javascript file I have written

<script type = "javascript" src = "mycode_2010.js">

However, I would like to replace 2010 with a variable so that for example I can detect the year and load the appropriate code e.g. mycode_2011.js rather than writing a new hard coded html page.

Is it possible please?

mrhoo
11-17-2010, 03:30 PM
<script type = "javascript" src = "mycode_2010.js"></script>
should be:
<script type = "text/javascript" src = "mycode_2010.js"></script>

or, in HTML5:
<script src= "mycode_2010.js"></script>



<script>
var y=new Date().getFullYear();
document.writeln('<script src="mycode_'+y+'.js"><\/script>');
</script>

By the way, this is a bad idea...

Philip M
11-17-2010, 03:46 PM
Well, of course it is possible!


<body onload = "loadjsfile()">

<script type = "text/javascript">

function loadjsfile(){
var thisYear = new Date().getFullYear();
var filename = "mycode_" + thisYear + ".js";
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", filename);
if (typeof fileref != "undefined") {
document.getElementsByTagName("head")[0].appendChild(fileref);
}
}

</script>

Longer than mrhoo's but could be executed other than at load time. For example, according to user's selection.

Is it always a bad idea?

Another way:-


<script type = "text/javascript" id="myscript"></script>

<script type = "text/javascript">
var thisYear = new Date().getFullYear();
var ms = document.getElementById("myscript");
ms.src = "mycode_" + thisYear + ".js ";
</script>


"He's an interesting player - he has unusually short back legs." - Football commentator

rps
11-17-2010, 08:08 PM
Thanks for your help. I can "play" with this. Why is it a bad idea incidentally? I'm simply trying to find a way of avoiding having to re-write code each year.

glenngv
11-17-2010, 08:24 PM
if (typeof fileref != "undefined") {
document.getElementsByTagName("head")[0].appendChild(fileref);
}

I wonder why you have to check for undefined. fileref will never be undefined or null regardless if the js file exists or not.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum