0

I have a script "myscript.js" which I'm embedding like this:

<script type="text/javascript" src="myscript.js" data-param="{'param1':true,'param2':false}"></script>

How can I get the value of data-param inside of myscript.js? I would prefer to do this without jQuery.

PS. I once saw something like this: <script src="myscript.js,param3"> - how would I get param3 if I did this?

glomad
  • 5,539
  • 2
  • 24
  • 38
kingkong
  • 1,537
  • 6
  • 27
  • 48
  • 1
    You could add an ID to your script tag, and use the normal document or JQuery selector approach – Marvin Smit Oct 29 '13 at 13:44
  • Maybe this answare can help you http://stackoverflow.com/questions/2190801/passing-parameters-to-javascript-files – Leonardo Silva Oct 29 '13 at 13:49
  • possible duplicate of [Get data attribute of script tag?](http://stackoverflow.com/questions/14904378/get-data-attribute-of-script-tag) – glomad Oct 29 '13 at 14:01

2 Answers2

1

Something like:

var param = document.getElementsByTagName("script")[0].getAttribute("data-param");

This assumes you only have 1 script (hence the [0]) -- if you have more, well, you'll have to loop and get the right value.

tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • 1
    You'd also want to use something like `JSON.parse(param)` if you want to treat that value as an object, and you'd have to use double quotes: `data-param="{\"param1\":true,\"param2\":false}"`. Single quotes around keys are not valid JSON and will not parse. – glomad Oct 29 '13 at 13:53
  • What in case of more then one script ? possible scripts before and after ? – kingkong Oct 29 '13 at 14:15
  • If you can assign IDs to your scripts: ` – glomad Oct 29 '13 at 14:33
  • Well, do you know what value you're going for? – tymeJV Oct 29 '13 at 14:34
0

Get the last script element in the page and use getAttribute to get the parameters. The last script element is always the current one, so you don't need to work with IDs.

// Get all script tags
var scriptElements = document.getElementsByTagName("script");
// Get the number of scripts
var numberOfScripts = scriptElements.length;
// The current script is the last script in the list
var currentScript = scriptElements[numberOfScripts - 1];
// Now you can retrieve the attribute
var param = JSON.parse(currentScript.getAttribute("data-param"));

This is the same, only shorter and less readable:

var scriptElements = document.getElementsByTagName("script");
var param = JSON.parse(scriptElements[scriptElements.length - 1].getAttribute("data-param"));
Butt4cak3
  • 2,389
  • 15
  • 15