Search code examples
javascriptscript-tag

What's the simplest <script> tag with params


I want to include a script tag, while providing a parameter to it. This is what I came up with so far

  1. Provide a parameter to script URL (cons: generate multiple JS files)

    <script src="http://example.com/something.js?P=123" type="text/javascript"></script>
    
  2. Hide parameter in script tag (cons: same as #1)

    <script src="http://example.com/scripts/123/something.js" type="text/javascript"></script>
    
  3. Google Analytics way (cons: ugly, complicated, global variables)

    <script type="text/javascript" charset="utf-8">
      var _something = _something || 123;
      (function() {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = 'http://example.com/something.js';
        var ss = document.getElementsByTagName('script')[0];
        ss.parentNode.insertBefore(s, ss);
      })();
    </script>
    

Solution

  • If the way the script is executed, depends on how it's called, you can add params like your option 1.

    Other ways are:

    <script params='{"abc": 123}' src="script.js"></script><!-- params is a non standard, non official attr that the script will read -->
    

    or

    <script>var _abc = 123;</script>
    <script src="script.js"></script>
    

    or even

    <script src="script.js#abc=123"></script>
    

    I have to agree with @outis though: load the same thing for everybody, always, and execute it like you/the client want(s) afterwards.