1

Sometimes you see code like this.

<script type="text/javascript" src="https://apis.google.com/js/plusone.js">
      {lang:'en', parsetags:'explicit'}
</script>

I'd like to know how it's possible to parse the object literal inside this script tag from the loaded script.

Robin Drexler
  • 4,307
  • 3
  • 25
  • 28
  • When the script is run search for the last script tag (?), or when the DOM is fully loaded search for the script tag with the src value you want. – TheZ Jul 03 '12 at 22:24
  • Related: http://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script and partially http://ejohn.org/blog/degrading-script-tags/ – ThiefMaster Jul 03 '12 at 22:26

1 Answers1

2
var scripts = document.getElementsByTagName('script');
var thisScriptTag = scripts[scripts.length - 1];
var data = thisScriptTag.textContent || thisScriptTag.innerText;
alert(data);

If you have JSON data you'd use JSON.parse() to convert the data to a JavaScript object. Note that the code must not be wrapped in a DOMready/onload event - it needs to run right when that <script> tag is processed.

The code to get the current script tag was taken from How may I reference the script tag that loaded the currently-executing script?

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636