Passing Querystring Style Parameters to a Javascript File

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

I have a javascript file that I reference in a flat HTML page. I would like to go through a parameter or two through the path to the script. Like this:

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

Not sure if this might work, but it would make my decision easier so others can take my script and implement it (maybe).

Cheers, Mike

+2
source share
2 answers

I don’t think that passing variables through the src attribute is possible out of the box without any additional code on your part (there is an article here if you are interested!). You could do the following, although you must provide the same functionality that you are looking for:

Define the "config" variables in one script block on the HTML page:

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

Link to external external JS file in the second block of the script:

 <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 } 
+3
source

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

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

and then read it in the jQuery file:

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

This is not exactly the same as passing it through a querystring, but is useful if this information is considered "meta-information" on an HTML page.

+1
source

Source: https://habr.com/ru/post/982525/


All Articles