2

I'd like to load and execute an external javascript file (Google Adwords's conversion script) only if a condition is met. Similar questions have already been asked, I've tried their solutions but it didn't work. I've the following code :

<script> 
        $(function() { 
            if ([condition]) { 
                $.getScript('//www.googleadservices.com/pagead/conversion.js'); 
            } 
        }); 
</script> 

The script is loaded but isn't executed. How do I do to execute it ?

I've tried to change getScript() with

var script = document.createElement("script" ); 
script.setAttribute("src", "//www.googleadservices.com/pagead/conversion.js" ); 
document.getElementsByTagName("head" )[0].appendChild(script); 

but it didn't work as well.

Thanks !

@VLAS: Oops pasted the wrong thing, corrected

@ejay_francisco: I already tried to create the script tag and append it to the head but it doesn't work

@Barar: I mean the page downloads the script file but doesn't execute it. Yes, if you want the full code :

<!-- Google Code for Formulaire Contact Conversion Page --> 
        <script type="text/javascript">
            /* <![CDATA[ */
            var google_conversion_id = [...];
            var google_conversion_language = "en";
            var google_conversion_format = "3";
            var google_conversion_color = "ffffff";
            var google_conversion_label = "[...]"; 
            var google_remarketing_only = false;
            /* ]]> */
        </script>
        <!-- <script type="text/javascript"  src="//www.googleadservices.com/pagead/conversion.js"></script> -->
        <script type="text/javascript"  src="//code.jquery.com/jquery.min.js"></script>
        <script>
        $(function() {
            if ([condition]) {
                $.getScript('//www.googleadservices.com/pagead/conversion.js');
                $("#google_conversion").attr('src','//www.googleadservices.com/pagead/conversion/[...]/?label=[...];guid=ON&amp;script=0');
            }
        });
        </script>
        <div style="display:inline;">
            <img id="google_conversion" height="1" width="1" style="border-style:none;" alt=""  src="#"/>
        </div>
user3782513
  • 23
  • 1
  • 4
  • How can it be loaded without being executed? That's what loading does. – Barmar Jun 27 '14 at 09:31
  • Why do you set src attribute on _regScript_ and append _script_ variables? – Vlas Bashynskyi Jun 27 '14 at 09:32
  • [this](http://stackoverflow.com/questions/24446439/how-to-remove-loaded-script-and-add-new-script/24446625#24446625) link might help you – Yaje Jun 27 '14 at 09:33
  • Do you set all the `google_conversion_XXX` variables before loading the script? – Barmar Jun 27 '14 at 09:36
  • your second argument to script.setAttribute must have http: in the beginning, is that a wrong pasted thing again? – Vlas Bashynskyi Jun 27 '14 at 09:36
  • 2
    @VLAS That's not true. Omitting `http:` means it will copy the protocol of the current page. It will use `http:` or `https:` depending on the current page's URL. – Barmar Jun 27 '14 at 09:38
  • 1
    Respond to comments in the comments. Commenters aren't notified when you respond to them in the question like that. – Barmar Jun 27 '14 at 09:39
  • Your code looks just like this answer: http://stackoverflow.com/a/5946563/1491895 and it works there. How do you know it's not executing? – Barmar Jun 27 '14 at 09:40
  • @Barmar: It's not executing because by loading the script normally, some URLs are shown in the browser network log, which are not there if i try to load the script conditionally – user3782513 Jun 27 '14 at 09:52

3 Answers3

2

In the long run you'd be better off using the proper asynchronous version of the adwords conversion script I think as it has been built specifically to handle these sorts of things. This way avoids any encoding mistakes and is easier to read and maintain.

So, based on this here is what I reckon you'd want (although I am no jQuery expert - I prefer to use standard javascript but hey each to their own):

<head>
  <!-- Add the async conversion script as usual - use async if you want --->
  <script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion_async.js" charset="utf-8"></script>
</head>

<!-- the rest of your site HTML and code -->

<script>
$(function() {
  if ([condition]) {
    window.google_trackConversion({
      google_conversion_id: "[...]",
      google_conversion_language: "en",
      google_conversion_format: "3",
      google_conversion_color: "ffffff",
      google_conversion_label: "[...]",
      google_conversion_value: 0,
      google_remarketing_only: false
    });
  }
});
</script>
matt1
  • 1,175
  • 7
  • 14
  • Forgot to answer, this worked thank you! I don't understand why Google doesn't put forward this version of the script, it's very useful in many cases – user3782513 Jul 03 '14 at 09:38
  • Glad it worked. They do distribute this version! It is at https://developers.google.com/adwords-remarketing-tag/asynchronous/ – matt1 Aug 11 '14 at 10:02
  • The link is dead :( ... But conversion_async.js still works! :) – bendodge May 02 '18 at 21:15
0

Try This:

<script type="text/javascript">
  $(document).ready(function(){ 
   if ([condition]) { 
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.googleadservices.com/pagead/conversion.js"; 
document.getElementsByTagName("head")[0].appendChild(script);
   } 
  }); 
</script>
0

Try this:

$(function() {
    if ([condition]) {
        $.getScript('//www.googleadservices.com/pagead/conversion.js', function() {
            $("#google_conversion").attr('src','//www.googleadservices.com/pagead/conversion/[...]/?label=[...];guid=ON&amp;script=0');
        });
    }
});

This doesn't set the src of #google_conversion until after the conversion.js script is loaded. If there's a dependency, you need to do them in the right order. You were doing this first, because $.getScript is asynchronous.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Mmh in fact didn't see that the calls in the network log came from the link in the image tag. Actually I think the script is executed, the problem is somewhere else as there's the error message "Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened. ". Do you have any more ideas ? – user3782513 Jun 27 '14 at 10:30
  • Sorry, no. I'm not sure why `conversion.js` would try to use `document.write()`. That's usually used by ad scripts that are replacing the document entirely, not scripts that just modify the page behavior. – Barmar Jun 27 '14 at 10:36