Javascript jQuery:确认.html()是否可添加
为了节省性能,我通过在用户将鼠标悬停在follow/like按钮上时添加社交链接来加载社交链接。例如:Javascript jQuery:确认.html()是否可添加,javascript,jquery,Javascript,Jquery,为了节省性能,我通过在用户将鼠标悬停在follow/like按钮上时添加社交链接来加载社交链接。例如: jQuery(document).ready(function(){ jQuery('.trigger').bind('click mouseover', function(){ jQuery(this).html('<script src="http://platform.twitter.com/widgets.js"></script>&
jQuery(document).ready(function(){
jQuery('.trigger').bind('click mouseover', function(){
jQuery(this).html('<script src="http://platform.twitter.com/widgets.js"></script><a href="https://twitter.com/twitter" class="twitter-follow-button" data-show-count="false" data-size="medium"> Follow @twitter </a>');
jQuery('.trigger').unbind('click mouseover');
});
});
您需要自己加载脚本,而不是以这种方式加载,然后检查脚本是否成功:
jQuery(document).ready(function($) {
$('.trigger').one('click mouseover', function(){
// we add just the HTML manually
$(this).html('<a href="https://twitter.com/twitter" class="twitter-follow-button" data-show-count="false" data-size="medium"> Follow @twitter </a>');
// and the script with jQuery
$.getScript("http://platform.twitter.com/widgets.js").fail(function(err) {
// react to errors here, for example set the .html
}).done(function(success) {
// here we can be sure the script loaded.
});
});
});
async
-设置此布尔属性以指示浏览器应异步执行脚本(如果可能)。它对内联脚本(即没有src属性的脚本)没有影响
作为常规代码检查,
ready
采用一个参数,您可以使用该参数来缩写jQuery(通常为$),您应该使用标准的.on
来支持不推荐的.bind
(和.off
来取消绑定)
更新,我已经意识到您使用
bind/unbind
(on/off
)对所做的工作本质上是一个one
,它在第一次触发事件时只触发一次,所以我将其更改为 .html()不输出任何内容
-未定义
,空字符串,空值?@Justinas你是什么意思?只需在此处尝试代码:--将光标悬停在侧栏上的社交链接上。请注意,作为JSFIDLE的服务似乎不允许.html()解析……非常感谢您发布这篇文章。为了完成,您能用您的.on
和.off
建议更新我的代码吗?不管怎样,我都要测试它并报告。@henrikpeterson如果您愿意,我可以制作一个简短的JSFIDLE来说明这一点(甚至是一个堆栈片段)。似乎另一个用户已经为我更新了答案(感谢redbmk),但是正如您所看到的非授权语法(常规语法),它只是更改了名称,。效果很好!很高兴向你学习!一个问题。我像这样加载Facebook按钮:jQuery(this.html(“”)代码>并且它也会被阻止。亨利克佩特森(Henrikpeterson)总的来说,有没有办法在这里实施这种方法?不,iFrame具有相同的源策略,这意味着未经允许,外部页面无法了解内部页面的任何信息。您可以直接向facebook广告元素(例如,facebook像素源)发出$.getScript
HTTP请求,然后检查是否加载了该请求。或者-如果twitter失败了,那么假设FB也不能工作。这可能也是我会做的。快乐编码。您可能还想考虑<代码> DEFER < /代码>有利于<代码>异步代码>代码>如果页面加载时用户将不做什么,请参阅差异。
jQuery(document).ready(function($) {
$('.trigger').one('click mouseover', function(){
// we add just the HTML manually
$(this).html('<a href="https://twitter.com/twitter" class="twitter-follow-button" data-show-count="false" data-size="medium"> Follow @twitter </a>');
// and the script with jQuery
$.getScript("http://platform.twitter.com/widgets.js").fail(function(err) {
// react to errors here, for example set the .html
}).done(function(success) {
// here we can be sure the script loaded.
});
});
});
<!--- NOTE THE 'async' --->
<script async src="http://platform.twitter.com/widgets.js"></script>
<a href="https://twitter.com/twitter" class="twitter-follow-button" data-show-count="false" data-size="medium"> Follow @twitter </a>