Expand my Community achievements bar.

Help shape the future of AI assistance by participating in this quick card sorting activity. Your input will help create a more effective system that better serves your needs and those of your colleagues.
SOLVED

Concatenating string with data element value

Avatar

Community Advisor

Hi guys, i want to load a script with dynamic values based on domain, so i have set up a data element with the different values based on document.locationHostname, it seems to work as expected and the value changes based on site domain.
running into some issues when trying to load the string in the HTML custom code of rule.

 

so this is the string, it will fail at the getVar portion of the string:

<script src='https://sripturl/rc/'+(_satellite.getVar('account_string')+'/scripts/s.js' type='text/javascript'></script>  

 

so what im after is a string that looks like this (given the data element value is 12345):

<script src='https://sripturl/rc/12345/scripts/s.js' type='text/javascript'></script>  

 

i guess theres some single double quotation issues here, or maybe its not possible to do? 
Any pointers appreciated!

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

There are a few problems, e.g. you have an opening "(" but no corresponding closing ")". But the main problem is that you're mixing HTML and JavaScript together.

I suggest using this JavaScript code instead:

var script = document.createElement('script');
script.src = 'http://sripturl/rc/' + _satellite.getVar('account_string') + '/scripts/s.js';
script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script);

Reference: https://stackoverflow.com/a/18784960

View solution in original post

3 Replies

Avatar

Correct answer by
Community Advisor

There are a few problems, e.g. you have an opening "(" but no corresponding closing ")". But the main problem is that you're mixing HTML and JavaScript together.

I suggest using this JavaScript code instead:

var script = document.createElement('script');
script.src = 'http://sripturl/rc/' + _satellite.getVar('account_string') + '/scripts/s.js';
script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script);

Reference: https://stackoverflow.com/a/18784960

Avatar

Community Advisor
Hi, great, this works, one thing to note though is that it will not work with Page Bottom or Page Top event , a direct call or DOM ready event works fine

Avatar

Community Advisor
@Sebastiane_Edberg_ it'll also work with DOM Ready or Window Loaded. The reason it doesn't work with Library Loaded nor page Bottom is that the browser may not have rendered the web page's DOM tree completely, so it cannot get the <head> element properly.