简体   繁体   中英

Use a JavaScript variable inside src of script tag

Google provides its script embed code to display a trends Map by placing this code in our site.

<script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330"></script>

The above code displays the trends map.

Notice the q=iphone in the above URL. I want to pass a JavaScript variable value instead of hard coding a fixed value like iPhone in this case.

How can I use a JavaScript variable inside the src of script tag?

I tried creating script programmatically, it injects the script code but the script does not get executed.

My try

document.body.appendChild(document.createElement('script')).src= varHavingScriptURL;

My try is in a JS Fiddle here .

The problem is, you can not do this after page load. Look at the source of the script

document.write('<iframe width="500" ... </iframe>');

So you need to do this as the page is rendering because of the document.write .

Now looking at what you did

document.body.appendChild(document.createElement('script')).src = varHavingScriptURL;

That is not going to work, you need to break it up

var scr = document.createElement('script');
scr.src = varHavingScriptURL;
document.getElementsByTagName("head")[0].appendChild(scr);

but again, it is not going to work because of the document.write.

Finally after hours of struggle, I found the solution using PostScribe.

 // jQuery used as an example of delaying until load.


$(function
 () {
// Build url params and make the ad call
  var str= "magic";
postscribe('#ad', '<script src=//www.google.com.pk/trends/embed.js?hl=en-US&q='+str+'&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330><\/script>');


});

Postscribe

Working Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM