Search code examples
javascriptgoogle-ads-api

Google Adwords Conversion after button click


I would like to load Google Adwords Conversion script after user clicks a button.

Here is the code:

<!-- Google Code for xyz Conversion Page -->
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 123;
var google_conversion_label = "abc";
var google_remarketing_only = false;
/* ]]> */
</script>
<script id="conversionScript" type="text/javascript" src="">
</script>

<script type="text/javascript">
document.addEventListener( 'wpcf7mailsent', function( event ) {
alert("OK");
document.getElementById("conversionScript").src="//www.googleadservices.com/pagead/conversion.js";
}, false );
</script>

I try to set the "src" atribute to the Conversion script after the button has been clicked, but it doesn't load the script. (Alert "OK" works)

Can anybody help to find out what is the problem? Thanks,


Solution

  • You have to create a new <script> element for it to work, just changing the src will not make the script run.

    // Initialize new script element
    let conversionScript     = document.createElement('script');
        conversionScript.src = '//www.googleadservices.com/pagead/conversion.js';
    
    // Append it to the DOM
    let head = document.getElementsByName('head')[0];
        head.appendChild(conversionScript);