我只想在满足条件的情况下加载并执行外部JavaScript文件(Google Adwords的转换脚本)。类似的问题已经被提出,我已经尝试了他们的解决方案,但它没有成功。我有以下代码:
<script>
$(function() {
if ([condition]) {
$.getScript('//www.googleadservices.com/pagead/conversion.js');
}
});
</script>
脚本已加载但未执行。我该怎么做才能执行它?
我尝试使用
更改getScript()var script = document.createElement("script" );
script.setAttribute("src", "//www.googleadservices.com/pagead/conversion.js" );
document.getElementsByTagName("head" )[0].appendChild(script);
但它也不起作用。
谢谢!
@VLAS:哎呀粘贴了错误的东西,纠正了
@ejay_francisco:我已经尝试创建脚本标记并将其附加到头部但它不起作用
@Barar:我的意思是该页面下载了脚本文件,但没有执行它。是的,如果你想要完整的代码:
<!-- 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&script=0');
}
});
</script>
<div style="display:inline;">
<img id="google_conversion" height="1" width="1" style="border-style:none;" alt="" src="#"/>
</div>
答案 0 :(得分:2)
从长远来看,你最好使用proper asynchronous version of the adwords conversion script,因为它是专门为处理这些事而构建的。这样可以避免任何编码错误,并且更易于阅读和维护。
所以,基于此,这是我认为你想要的(虽然我不是jQuery专家 - 我更喜欢使用standard javascript但是他们各自都是自己的):
<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>
答案 1 :(得分:0)
试试这个:
<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>
答案 2 :(得分:0)
试试这个:
$(function() {
if ([condition]) {
$.getScript('//www.googleadservices.com/pagead/conversion.js', function() {
$("#google_conversion").attr('src','//www.googleadservices.com/pagead/conversion/[...]/?label=[...];guid=ON&script=0');
});
}
});
在加载src
脚本之前,这不会设置#google_conversion
的{{1}}。如果存在依赖关系,则需要按正确的顺序执行。你首先这样做,因为conversion.js
是异步的。