繁体   English   中英

jQuery:确认.html()是否可添加

[英]jQuery: confirm if .html() is addable

为了节省性能,我在用户将鼠标悬停在“关注/喜欢”按钮上时通过添加社交链接来加载社交链接。 例:

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');

    });

});

工作正常。 实际上,您也应该这样做。

问题是在Firefox中使用隐身模式时,它会阻止社交链接,因此.html()不会输出任何内容。

某些浏览器插件的相同问题阻止了社交链接。

无论如何,是否有找到.html()是否输出代码的信息, 否则 ,只需添加一个链接即可:

jQuery(this).html('<a href="">Follow</a>');

您需要自己而不是通过这种方式加载脚本,然后检查脚本是否成功:

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.
        });
    });

});

请注意,一个特别聪明的广告拦截器可以拦截该请求并返回一个空响应,而不是404,但实际上没有响应。

我也通常不同意您的说法,即应该将它们延迟加载-通常,将async这个词添加到脚本中通常是可以的,并且不会阻止页面加载并稍后加载:

<!--- 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>

async设置此布尔值属性以指示浏览器应尽可能异步执行脚本。 它对内联脚本(即不具有src属性的脚本)没有影响。

来自MDN


作为一般的代码审查, ready采取哪些您可以使用短名称的jQuery(如$通常)的参数,你应该使用标准.on赞成不赞成不赞成.bind (和.off为解除绑定)。


更新,我已经意识到您对bind/unbindon/off )对所做的本质上是one只触发一次事件的对-因此我将其更改为该事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM