10

The question says it all. How to update the "src" of script tag using jQuery. Let say, I have a script,

 <script id="somescript" type="text/javascript" src=""></script>

So when I a click on a button, the src of the script must be added. Like,

 <script id="somescript" type="text/javascript" src="linktoscript.js"></script>

I am doing it with a click handler like this, using the following code.

$("#somescript").attr("src","linktoscript.js");

It actually updates the src but when I check it via firebug, it tells me to refresh the page to get the script working.

Research:

After some research, I've found $.get() of jQuery would do the job and yes, it loads the script. But it is not getting my job done.

The Actual Problem:

I am trying to load Google's conversion code using Ajax on successful form submission.

Here is the part of the Ajax script that should work for the Google's conversion code.

                    if (res == "yes") {
                        $('#success').fadeIn().delay(5000).fadeOut();
                        $('#regform')[0].reset();
                        window.location.href = '#'; 
                        /* <![CDATA[ */
                        var google_conversion_id = xxxxxxxxx;
                        var google_conversion_language = "en";
                        var google_conversion_format = "2";
                        var google_conversion_color = "ffffff";
                        var google_conversion_label = "CiaXCOXjzlcQy__EyQM";
                        var google_remarketing_only = false;
                        /* ]]> */

 $.getScript("http://www.googleadservices.com/pagead/conversion.js");   
  }

It loads the conversion script but when I check it from firebug, all the values of the conversion variables are null. So I am giving it a try by putting all of the conversion code into the html file and then load the conversion script like,

 <script type="text/javascript">
  /* <![CDATA[ */
  var google_conversion_id = xxxxxxxxx;
  var google_conversion_language = "en";
  var google_conversion_format = "2";
  var google_conversion_color = "ffffff";
  var google_conversion_label = "CiaXCOXjzlcQy__EyQM";
  var google_remarketing_only = false;
  /* ]]> */ 
 </script>

 <script type="text/javascript" src="#"></script> <!--Update this src-->

 <noscript>
  <div style="display:inline">
   <img height="1" width="1" style="border-style:none;" alt="" src="#" />
  </div>
 </noscript>

Any Help?

Link:

Here is the link to the live site : Link

Update: This is what I get. In the firebug's script panel, after form submission, enter image description here

Awais Umar
  • 1,941
  • 3
  • 19
  • 45
  • Have a look to this answer: http://stackoverflow.com/questions/14521108/dynamically-load-js-inside-js – Joerg Jan 17 '15 at 08:15
  • Provide online link which replicates your issue so it could be debugged – A. Wolff Jan 17 '15 at 08:28
  • @A.Wolff. Thank you for your concern. I have updated the post and have inserted the link. – Awais Umar Jan 17 '15 at 08:35
  • After some quick search, it appears that this script is using document write function, so calling it once document fully loaded as downside effect. Override this method is not good advice but should fix your issue. See e.g this: http://articles.adamwrobel.com/2010/12/23/trigger-adwords-conversion-on-javascript-event Hope that's help – A. Wolff Jan 17 '15 at 08:38
  • @A.Wolff. I have tried the method you have recommended. Still, no luck. But one strange thing. I have inserted the conversion code directly into document.ready function just to check it. No, Ajax or other complex things. Strange thing is that I still see null values. Could it be possible that the provided code is not right? What do you think? – Awais Umar Jan 17 '15 at 09:01
  • @Symbolwdd Ya it could be outdated but i see that conversion script still using document write so i'm not sure what's going wrong. – A. Wolff Jan 17 '15 at 09:04
  • @A.Wolff. Can you kindly re-check on the link I have provided. I have updated the scripts and files. Now, the code has been added directly into html file and no script work on it. So it must load with the page. Can you check? It loads the conversion.js but still, the values are null. Except two. – Awais Umar Jan 17 '15 at 09:20
  • It would be better if you provide a minimalistic code to replicate issue. Currently, i have not so much time in hand nor envy to debug a whole website and it would be anyway completly useless for the SO futur readers. Just be aware, i've no idea how works google conversion and what it is supposed to do. I hope someone with more knowledge regarding it would be able to help you – A. Wolff Jan 17 '15 at 09:29
  • @Symbolwdd Does your last approach, putting the JavaScript directly in the HTML, work? You didn't tell us what the outcome was. You just told us that you tried it. – JLRishe Jan 17 '15 at 15:38
  • @Symbolwdd Please also tell us how you are going about verifying that _"all the values of the conversion variables are null"_ since we have no idea what they are or how to check their values. – JLRishe Jan 17 '15 at 16:11
  • @JLRishe, Thank you for taking interest. Yes, when I added the code directly into the html, the conversion started showing up. I am updating my post and will put a screenshot here. – Awais Umar Jan 19 '15 at 07:10

3 Answers3

3

It would appear that the Google conversion script relies on google_conversion_id, google_conversion_language, etc. to be available as global variables. Presuming that the code you have there is executing inside a function (which would make sense if this is inside an event), the code you have there will not work because the variables will be local to the function they are in, and the google code will have no way to get at them.

There are two things you can do.

One is to define those variables in the global scope ahead of time, i.e. do this:

<script type="text/javascript">
  /* <![CDATA[ */
  var google_conversion_id = xxxxxxxxx;
  var google_conversion_language = "en";
  var google_conversion_format = "2";
  ...
</script>

(you can also put these in an external script file and load that file when the page loads:

If you do that, you can load the google conversion script whenever you want, and it will be able to access those variables:

$.getScript("http://www.googleadservices.com/pagead/conversion.js");   


The other option is to assign your variables to the window object right before you load the script, which is equivalent to putting them in the global scope:

if (res == "yes") {
    $('#success').fadeIn().delay(5000).fadeOut();
    $('#regform')[0].reset();
    window.location.href = '#'; 

    window.google_conversion_id = xxxxxxxxx;
    window.google_conversion_language = "en";
    window.google_conversion_format = "2";
    window.google_conversion_color = "ffffff";
    window.google_conversion_label = "CiaXCOXjzlcQy__EyQM";
    window.google_remarketing_only = false;

    $.getScript("http://www.googleadservices.com/pagead/conversion.js");   
}


Note: regarding the issue that this question was originally about, you can't load a script by changing the src attribute of an existing script element:

http://jsfiddle.net/5vf6b924/

Once a script element has loaded whatever is indicated by the src (even if it's #), it is essentially "used up" and won't load anything else.

What you can do is to create a new script element and add it to the DOM:

http://jsfiddle.net/ydu52cn1/

That should succeed in loading the script (asynchronously).

As you've found, jQuery also provides the $.getScript convenience method for this.

JLRishe
  • 90,548
  • 14
  • 117
  • 150
1

At the end, the following did the job for me. Thanks to JLRishe and A. Wolff for their support.

In my previous code, there were two problems.

  1. I was not inserting the "img" element along with other conversion code. (Silly mistake but I was working with conversion code for the first time. So please pardon me).
  2. Inserting src of the "img" tag in the default format would give error. The default &amp; would render Invalid URL encode error upon AJAX response. Thanks for Tag Assitant. Rather than using &amp;, use & directly like this.

www.googleadservices.com/pagead/conversion/xxxxxxxxx/?label=CiaXCOXjzlcQy__EyQM&guid=ONscript=0

Here is what finally worked for me.

    if (res == "yes") {
        $('#success').fadeIn().delay(5000).fadeOut();
        $('#regform')[0].reset();   

        <!-- Google Code for Lead Conversion Page -->                           
         /* <![CDATA[ */
         window.google_conversion_id = xxxxxxxxx;
         window.google_conversion_language = "en";
         window.google_conversion_format = "2";
         window.google_conversion_color = "ffffff";
         window.google_conversion_label = "CiaXCOXjzlcQy__EyQM";
         window.google_remarketing_only = false;
         /* ]]> */
         $.getScript("//www.googleadservices.com/pagead/conversion.js");                            

         window.scriptTag2 = document.createElement('noscript');
         window.imgTag = document.createElement('img');
         imgTag.height = 1;
         imgTag.width = 1;
         imgTag.border = 0;
         imgTag.src = "//www.googleadservices.com/pagead/conversion/xxxxxxxxx/?label=CiaXCOXjzlcQy__EyQM&guid=ONscript=0";                                  

    }

I hope it will help the someone else with the same problem. Thank you.

Community
  • 1
  • 1
Awais Umar
  • 1,941
  • 3
  • 19
  • 45
0

You could append the script tag to the DOM

if (yourCondition === true) {
$('head')
    .append($('<script id="somescript" type="text/javascript" src="linktoscript.js"></script>'));
}

The script is loaded at the moment it is appended, that way you have total control of when it is loaded.

chiliNUT
  • 17,144
  • 11
  • 59
  • 92
  • I have tried that also. Result is the same. Null values of all the conversion variables – Awais Umar Jan 17 '15 at 08:16
  • can you post your complete script, or a fiddle? I don't know how the flow/cascade of events is working, so I wouldn't be able to help until I know that; I can't try to see why those variables are null if I don't know where and when they are accessed relative to when the script is dynamically added – chiliNUT Jan 17 '15 at 08:18
  • I have updated my post and have provided link to the live site. You might be able to fully check now. – Awais Umar Jan 17 '15 at 08:36