Search code examples
javascriptjqueryvariablesattributesembed

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.


Solution

  • 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