javascript - Load and execute conditionally an external js file -
i'd load , execute external javascript file (google adwords's conversion script) if condition met. similar questions have been asked, i've tried solutions didn't work. i've following code :
<script> $(function() { if ([condition]) { $.getscript('//www.googleadservices.com/pagead/conversion.js'); } }); </script>
the script loaded isn't executed. how do execute ?
i've tried change getscript()
var script = document.createelement("script" ); script.setattribute("src", "//www.googleadservices.com/pagead/conversion.js" ); document.getelementsbytagname("head" )[0].appendchild(script);
but didn't work well.
thanks !
@vlas: oops pasted wrong thing, corrected
@ejay_francisco: tried create script tag , append head doesn't work
@barar: mean page downloads script file doesn't execute it. yes, if want full code :
<!-- google code 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&script=0'); } }); </script> <div style="display:inline;"> <img id="google_conversion" height="1" width="1" style="border-style:none;" alt="" src="#"/> </div>
in long run you'd better off using proper asynchronous version of adwords conversion script think has been built handle these sorts of things. way avoids encoding mistakes , easier read , maintain.
so, based on here reckon you'd want (although no jquery expert - prefer use standard javascript hey each own):
<head> <!-- add async conversion script usual - use async if want ---> <script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion_async.js" charset="utf-8"></script> </head> <!-- rest of site html , 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>
Comments
Post a Comment