Lourens
Lourens

Reputation: 13

Add variables to a .js file

I'm looking for a way to post variables in an external .js file.

Something like:

<script type="text/javascript" src="/js/script-starter.js?var=value"></script>

And then I'd like to call var (and thus, value). Is this possible in any way?

Thank you!

Upvotes: 1

Views: 966

Answers (5)

thecodeparadox
thecodeparadox

Reputation: 87073

function getJSPassedVars(script_name, varName) {
    var scripts = $('script'),
        res = null;

    $.each(scripts, function() {
        var src = this.src;
        if(src.indexOf(script_name) >= 0) {
            varName = varName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
            var string = new RegExp("[\\?&]"+ varName +"=([^&#]*)"),
                args = string.exec(src);
            if(!args.length) { 
                res = null; 
            } else { 
                res = args[1]; 
            }
        }
    });
    return res;
}

console.log(getJSPassedVars('script-starter.js', 'var'));

in my case my app folder structure is like following:

MyApp/
     index.html
     jquery.js
     my.js

above function is within my.js with console.log and include it within index.html.

Upvotes: 0

Kalzem
Kalzem

Reputation: 7492

Why don't you put the variables in a hidden a or p

<a id="myHiddenVar" style="display:none;">variables</a>

Then in your .js you access it with

var obj = document.getElementById("myHiddenVar").innerHTML;

or the jQuery style

var obj = $("#myHiddenVar").text();

Upvotes: 0

VisioN
VisioN

Reputation: 145408

How about declaring the variable before script file loading:

<script type="text/javascript">var myVar = "Value"</script>
<script type="text/javascript" src="/js/script-starter.js"></script>

So you can use this variable in your script. Possibly this is one of the easiest ways.

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

it could be possible if that script is a serverside script that receives the variable in querystring and returns a javascript code as output

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038920

Yes, it is possible. You will have to look for all script tags in the DOM (make sure the DOM is loaded before attempting to look in it) using the document.getElementsByTagName function, loop through the resulting list, find the corresponding script and parse the src property in order to extract the value you are looking for.

Something along the lines of:

var scripts = ​document.getElementsByTagName('script');
​for (var i = 0; i < scripts.length; i++)​ {
    var src = scripts[i].src;
    // Now that you know the src you could test whether this is the script
    // that you are looking for (i.e. does it contain the script-starter.js string)
    // and if it does parse it.
}​

As far as the parsing of the src attribute is concerned and extracting the query string values from it you may use the following function.

Upvotes: 8

Related Questions