I have a couple of JavaScript functions that I would like to reuse on multiple different pages, so I created an external .js file for the functions. I was wondering if it was possible to change the global variables of that javascript without changing the actual .js file. Here’s an example of what I mean:
Suppose I have this tag for my external JavaScript:
<script src="myscripts.js"></script>
Could I somehow define the global variables for the scripts in the <script> tag like so?
<script src="myscripts.js">
sampleglobalvariable = "somevalue";
sampleglobalvariable2 = "somevalue2";
</script>
Or like so?
<script src="myscripts.js"></script>
<script>
sampleglobalvariable = "somevalue";
sampleglobalvariable2 = "somevalue2";
</script>
Or would I have to define them inside the actual myscripts.js file?
You can do this:
myscripts.jswill have access to the global variables defined before.Alternatively you can turn
myscripts.jsinto a server-side script (written in PHP for example). That would let you pass parameters like this:The server-side script would then have to read
$_GET['foo']and$_GET['bar']and echo custom generated javascript back: