6/05/2014

[JS] Get Parameters in a JavaScript Script Tag

In google-code-prettify, you can specify the code language and skin just in one line. No extra configuration is necessary since the parameters is already appended to the URL.
<script src="svn/loader/run_prettify.js?lang=css&skin=sunburst"></script>
So how does the JS file know the parameters appended to its URL? You can just call the function getScriptParams(..) to get the parameters in JS object format.
This will get JS object:
console.log(getScriptParams('run_prettify.js')); 
Here is implementation of getScriptParams(..).
function getScriptParams(scriptFileName) {
   // Get all script tag
  var scripts = document.getElementsByTagName('script');
  var result = {};
  for(var i = 0; i < scripts.length; ++i) {
     // Check if the file name is the same as scriptFileName
    if(scripts[i].src.indexOf(scriptFileName) !== -1) {    
      // Get the parameters string     
      var urls = scripts[i].src.split('?');
      if(urls.length == 2) {
        var parameters = urls[1].split('&');        
        for(var j=0; j< parameters.length; ++j) {
          var pair = parameters[j].split('=');
          result[pair[0]] = pair[1];
        }
      }
      break;
    }
  }
  return result;
}