0

I wanna know is this possible I pass get parameters for a javascript file and use them in codes? I have this in html:

<script type="text/javascript" src="/javafile.js?q=somtext"></script>

know how I use this "q" parameter in my script codes? is this possible?

IVIR3zaM
  • 567
  • 9
  • 23

3 Answers3

4

You can either:

  1. Generate the JS dynamically with a server side language and read the query string there
  2. Assume that the JS is the last <script> element so far in the DOM and parse document.scripts[document.scripts.length - 1].src

Note that if the script element has been added dynamically (i.e. with JS), it might not be the last script in the DOM.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • thanks a lot. I seen in firebug that every javascript file in request send with a "_" parameter that have a a time-stamp. what do this parameter? – IVIR3zaM Feb 15 '12 at 14:11
  • 1
    @IVIR3zaM — That isn't standard. Something is probably adding it as a cache buster. – Quentin Feb 15 '12 at 14:17
1

I think Quentin's suggestion is the answer to your question.

I usually use an alternative way for this, which may also help you:

Make sure that your javascript is written in a library form, and make sure that you have an instantiate method/function inside your javascript that allows you to pass parameters (or better, as an object)

// on dom load:
library.init({ var1: value1, var2: value2});

This allows you also to load your javascript in a different way, and allows for cleaner code.

Arend
  • 3,741
  • 2
  • 27
  • 37
0

Or you can use option 3: use a library that has this functionality, e.g. MooTools: http://mootools.net/docs/more/Types/String.QueryString

Lennart
  • 1,018
  • 1
  • 12
  • 27
  • 2
    It looks like it's just an utility function for `string` -> `object` conversion; you'd still have to obtain the actual path with the values first. – pimvdb Feb 15 '12 at 14:09