Brad Thomas
Brad Thomas

Reputation: 103

How do I set the src address dynamically?

I am trying to grab information from the page url to set the src for a data file.

So, say page url is: page.html?x=data_file_3 (The ideas is I could change the url to access other data files: data_file_4, etc.)

I grab the "data_file_3" part of the url and put it in a variable: (the code I use for this works fine -- so result is) folder = "/data_file_3/content.js" -- the content of this file is just an array

Then I try this:

<script id="url" type="text/javascript"></script>

<script language="javascript">
...
var u = document.getElementById('url');
u.src = folder;
...
</script>

But this doesn't work (the array data does not show up on the page). I put this code right where I used to hard code:

<script type="text/javascript" src="/data_file_3/content.js"></script>

The hard-coded version works. Any ideas about how I can do this?

Upvotes: 3

Views: 432

Answers (1)

Geuis
Geuis

Reputation: 42277

Sounds like you are trying to create script tags dynamically.

var scr = document.createElement('script');
    scr.src = 'script_path';

document.getElementsByTagName('head')[0].appendChild(scr);

You can wrap this in a function where 'script_path' is whatever you're path you're passing in.

Note also that 'text/javascript' is not required. All browsers understand that its javascript.

Upvotes: 6

Related Questions