2

Not sure if this is possible or even if I should do it, but I think it's quite interesting.

I have a javascript file which I'm referencing in a flat HTML page. I'd like to pass in a parameter or two via the path to the script. Like this;

<script src="/scripts/myJavascriptFile.js?config1=true" type="text/javascript"></script>

Not really sure if it can work but it would make my solution a little easier for others to take my script and implement (arguable).

Cheers, Mike

Mike Mengell
  • 2,310
  • 2
  • 21
  • 35

2 Answers2

3

I don't think that passing in variables via the src attribute is possible out of the box without some extra coding on your part (there is an article here if you are interested!). You could do the following though, which should provide the same functionality as you are looking for:

Define your "config" variables in a single script block on your HTML page:

<script type="text/javascript">
  var config1 = true;
</script>

Reference your external JS file in a second script block:

<script src="/scripts/myJavascriptFile.js" type="text/javascript"></script>

Add this code to your external JS file to reference the "local" variable in your HTML:

var conf1 = window.config1;

if (conf1) {
  // Do stuff
}
Matt Weldon
  • 1,413
  • 11
  • 18
1

This is a variation on Matt's answer. I have a similar case where I need a jQuery file to use a value that is generated in the HTML (by Razor in this case). I write the value to a meta tag, generated as it is from the controller:

<meta name="sessionId" content="@ViewBag.SessionId">

and then read it in the jQuery file:

var sessionId = $("meta[name=sessionId]").attr("content");

It's not quite the same as passing it in by querystring, but useful if that information is considered "meta-information" of the HTML page.

Ralph Lavelle
  • 5,718
  • 4
  • 36
  • 46