View Full Version : vary call parameter

11-17-2010, 03: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?

11-17-2010, 04: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>

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

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

Philip M
11-17-2010, 04: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("src", filename);
if (typeof fileref != "undefined") {


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 ";

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

11-17-2010, 09: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.

11-17-2010, 09:24 PM
if (typeof fileref != "undefined") {

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