Reputation: 25348
Our service offers the ability to drop in some javascript on your page and display some tracking data, but I'd like for customers to be able to embed multiple instances of the embed code on the same page.
The problem right now is that I can't include the same variables names on the page.
For instance:
<script type="text/javascript">
var ttp_number = "1Z8E26R80281495993"; // Tracking number
var ttp_key="123456";
(function(){
document.write('<div id="ttp"></div>');
s=document.createElement('script');
s.type="text/javascript";
s.src="http://c.trackthepack.com/j/e?" + Math.random();
setTimeout("document.getElementById('ttp').appendChild(s);",1);
})()
</script>
Then if they wanted to be able to embed that again, I'd have to change all variable names:
<script type="text/javascript">
var ttp_number_001 = "446888240962"; // Tracking number
var ttp_key_001="123456";
(function(){
document.write('<div id="ttp_001"></div>');
s_001=document.createElement('script');
s_001.type="text/javascript";
s_001.src="http://c.trackthepack.com/j/e?" + Math.random();
setTimeout("document.getElementById('ttp_001').appendChild(s_001);",1);
})()
</script>
I'm okay with having them change the contents of the function()
block, but the ttp_number
and ttp_key
need to stay the same variable name.
Right now, when I have multiple embeds on the page, they all inherit the contents of the variables in the last embed code.
So, the ultimate question here...how do I fix that?
Upvotes: 0
Views: 482
Reputation: 12195
Why not declare the variables in the function body. Then they're only scoped to that function. You can still set them to different values when you dump the script into the HTML.
I know you mention/imply that the user can edit the function (for some reason) but that just seems like a world of hurt to me, so I'm hoping that that's not actually the case.
Upvotes: 1
Reputation: 16407
Why are you cachebusting with Math.random()
? Does the JavaScript at http://c.trackthepack.com/j/e
change often? If not, you should let the cache do its job.
But if so, could you make it dynamic enough to inspect the arguments it's called with and use those arguments directly, instead of relaying them via the global window
object, so that you load http://c.trackthepack.com/j/e?n=446888240962&k=123456
and it doesn't have to look them up when the script runs?
Upvotes: 0