Search code examples
javascriptquery-stringgetelementbyidsrc

How to add script src dynamically with getElementById?


Go easy on me - I don't spend a lot of time in javascript. :D

I am trying to write a script that will build a JS call based on a URL query, but cannot get the script src to update.

For example, if someone visits https://example.com/page?aid=ABC123, I want to create a script call that would function akin to: <script type='text/javascript' src='https://example.com/script.js?aid=ABC123'></script> But I need that call to be dynamically built based on the "aid" variable in the URL.

My "page" code looks like this:

<script type='text/javascript' src='' id='hwContent'></script>
<script type='text/javascript'>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const artid = urlParams.get('aid');
var url = "https://example.com/js.php?aid=";
document.getElementById('hwContent').src = url + artid;
</script>

For the moment while I'm testing, the "script.js" code is just a basic "success!" message using document.write - I haven't even gotten to seeing if the "aid" makes it through to the script file.

If I go direct to the script URL, it works. If I hard code the script URL into the script src field, it works. But as soon as I leave the src field empty and rely on getElementById to insert the url into the src field, nothing happens - the area that should display the "success!" message is just blank. Chrome inspector shows no JS errors.


Solution

  • Get artid like you did, create a script tag and add it to document.head:

    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const artid = urlParams.get('aid');
    var url = "https://example.com/js.php?aid=";
    var s = document.createElement( 'script' );
    s.setAttribute( 'src', url + artid );
     document.head.appendChild( s );