title: Pass URL parameters to script using Javascript include
body: <p>I'm trying to create a javascript tracker that can be included on any page, that will pass the variables "ref" and "aff" from the URL to the PHP code that does the tracking.</p>
  
  <p>This code works perfectly for my purposes on PHP pages:</p>
  
  <pre><code>&lt;script type="text/javascript" src="//www.foo.com/reftracker.php?ref=&lt;?= $_GET['ref'] ?&gt;&amp;amp;aff=&lt;?= $_GET['aff'] ?&gt;"&gt;
  &lt;/script&gt;
  &lt;noscript&gt;
  &lt;div style="display:inline;"&gt;
  &lt;img height="1" width="1" style="border-style:none;" alt="" src="//www.foo.com/reftracker.php?ref=&lt;?= $_GET['ref'] ?&gt;&amp;amp;aff=&lt;?= $_GET['aff'] ?&gt;"/&gt;
  &lt;/div&gt;
  &lt;/noscript&gt;
  </code></pre>
  
  <p>The issue is that I also need to add the tracker to non-PHP pages, so I need a pure Javascript solution to pass those URL parameters into src attributes.</p>
  
  <p>[EDIT]</p>
  
  <p>For anyone interested, here is the solution I ended up with:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
      function fooParamParse(val) {
          var result = '', tmp = [];
          location.search.substr(1).split("&amp;").forEach(function (item) {
              tmp = item.split("=");
              if (tmp[0] === val) result = decodeURIComponent(tmp[1]);
          });
          return result;
      }
  
      var script = document.createElement('script');
      document.getElementsByTagName('head')[0].appendChild(script);
      script.src = "//www.foo.com/reftracker.php?ref="+fooParamParse('ref')+"&amp;amp;aff="+fooParamParse('aff')+"";
  &lt;/script&gt;
  </code></pre>