简体   繁体   English

jQuery使用图像src attr()的用法加载太慢

[英]jQuery Loading Too Slowly with Image src attr() Usage

I'm building an eCommerce store and I've written a small piece of jQuery to change the SRC the logo for the home page only. 我正在建立一家电子商务商店,并且编写了一小段jQuery来仅将SRC徽标更改为首页。 The issue is that when I load the page I can see the incorrect logo load before the new SRC is applied. 问题是,当我加载页面时,在应用新的SRC之前我可以看到不正确的徽标加载。 I have recorded the issue here: 我在这里记录了这个问题:

https://app.hyfy.io/v/abmoLf1Q35/?p=1 https://app.hyfy.io/v/abmoLf1Q35/?p=1

jQuery: jQuery的:

<script>
    jQuery(document).ready(function() {
        if (top.location.pathname === '/') {
            jQuery(".logo img").attr("src", "newsrc.png");
        }
    });
</script>

Would I be correct in saying that for the jQuery to work the logo needs to have loaded first, which is why this is an issue? 我要正确地说,要使jQuery正常工作,必须先加载徽标,这就是为什么这是一个问题?

Either way, could anybody advise if it's possible to have the jQuery take priority or suggest a better way of achieving what I need to here? 无论哪种方式,有人可以建议是否可以让jQuery优先考虑还是建议一种更好的方式来实现我在这里需要的功能?

I appreciate the time taken to respond, thank you very much. 我感谢您花时间作出回应,非常感谢。

Yes, jquery would need to target an existing element to affect it. 是的,jquery需要针对一个现有元素来影响它。

in other words, the logic goes: 1. load image asset 2. alter source via jquery 换句话说,逻辑是:1.加载图像资产2.通过jquery更改源

if you have access to the css, you can put a display none on the .logo then when jquery alters the source, add a display:block via .css 如果您有权访问CSS,则可以在.logo上不显示任何内容,然后当jquery更改源代码时,通过.css添加display:block

<style>
    .logo img{
       display:none;
    }
</style>
<script>
    jQuery(document).ready(function() {
        if (top.location.pathname === '/') {
            jQuery(".logo").css('display', 'block').find('img').attr("src", "newsrc.png");
        }
    });
</script>

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

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