Setting script src dynamically

Suppose you need to call some JavaScript code on your page such as:

  <script src"somecode.js"></script>

However, the somecode.js is different based on other parameters on your page. So you would need to pass a variable rather than the static string to the src. If you just replace somecode.js, with a variable name, you code will not be called.

The following example shows how you can manipulate DOM to define src so that your code runs.

<script id="mycode"></script>
<script type="text/javascript">
// dynamic source is defined by a previous javascript code on the page
document.getElementById('mycode').src = dynamicsource;

Technologies: