Skip to content
Advertisement

Change script “src” by URL param and make it functional

I am thinking if it’s possible for doing this on a static website,
I have the link of

https://www.example.com?year=2022&week=05

and the main HTML is

<h4 style="color:#FFD700"><strong>TITLE</strong><br></h1>
                        <h3 id="1testing"></h3>
                        <h6 id="2testing"></h6>

// skipped

<script id="results" src="path/to/script/202205.txt"></script>

Now, I wanna make it to update according to the URL Param, I’ve got a URL Param (and update the code above) by

const queryString = window.location.search;
                console.log(queryString);
                const urlParams = new URLSearchParams(queryString);
                const yrs = urlParams.get('year')
                const wks = urlParams.get('week')
                console.log(yrs);
                console.log(wks);
                document.getElementById('results').src = "path/to/script/" + yrs + "/" + wks + ".txt"

The txt files are in the format of

document.getElementById("date").innerHTML =// date
"date";
            
// Number 1
document.getElementById("1testing").innerHTML =// 1testing
"1testing";
document.getElementById("2testing").innerHTML =// 2testing
"2testing";

//so on...

However, the trouble I’m having is that, the src tag updated AFTER loading and the content is simply not updating, possibly because of the scripts not in order, however I’m not having much knowledge on this, anyone could help with a solution on this?

Answer

I think you should remove the script tag and re-add the updated one.

  let oldScriptTag = document.getElementById('results');

  let newScriptTag = document.createElement('script');
  newScriptTag.id = 'results';
  newScriptTag.src = 'path/to/script/' + yrs + '/' + wks + '.js';
  newScriptTag.textContent = '//script';

  var body = document.getElementsByTagName('body')[0];

  oldScriptTag.remove();

  body.appendChild(newScriptTag);
Advertisement