Mando
Mando

Reputation: 11722

Static javascript tag with dynamically constructed URL

I have a static script declaration as a requirement, is it possible to have its URL dynamically constructed once browser wants to download it?

<script async src='https://my-known-host.com/script.js?param1=<dynamicValue>'
</script>

This parameter is generated on the client and let's say I want it to be just a random number.

  1. I want to generate random on client side because server caches pages and this request should have a unique random number every time paged is loaded (even from cache)
  2. I need to have it statically declared in order to start the download right away (even before browser parsed to the line of declaration)

Is it possible?

Upvotes: 0

Views: 110

Answers (2)

Vic
Vic

Reputation: 723

<head>
    <script>
            $("head").append($("<script>", {async: true, src: "test.js?params=" + Math.random()}));
    </script>
    <script async src="test.js?params=0.524902342"></script> <!-- parse-able result from the script below -->
</head>

Sorry, I provided jQuery, but this or a vanilla approach should get the job done. The trick is to run JavaScript in head that would append <script src="example.js?" + random></script> to head.

After the browser runs that, it would parse your parameterized <script> at the end of the head tag.

I tested it myself and my browser made a request to test.js?params=0.3607864086033945

Hope that solves it!

EDIT:

If you don't want the script to be at the end of head, you can also do this. Very important that you let the browser parse <script id="randScript" async></script> first.

<script id="randScript" async></script>
<script>
    $("#randScript").prop("src", "test.js" + Math.random()); //jQuery
    document.getElementById("randScript").src = "test.js" + Math.random(); //vanilla
</script>

Upvotes: 1

Josh Beam
Josh Beam

Reputation: 19802

Yeah, a common approach is to write a script that injects the script tag. Something like this:

<script type="text/javascript">

setTimeout(function(){
  var a = document.createElement("script");
  var b = document.getElementsByTagName("script")[0];

  // this adds some number, for example
  // you can tweak it to be a random number if you want
  a.src = document.location.protocol +
  "my-known-host.com/script.js?param1=" +
  Math.floor(new Date().getTime()/3600000);

  a.async = true;
  a.type = "text/javascript";
  b.parentNode.insertBefore(a,b)
}, 1);

</script>

I actually took this example script from an analytics provider (crazyegg.com), but Google Analytics does a similar approach. In other words, it's a common thing.

Upvotes: 1

Related Questions