matt136 matt136 - 1 month ago 12
HTML Question

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. The issue is that when I load the page I can see the incorrect logo load before the new SRC is applied. I have recorded the issue here:

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

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?

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?

I appreciate the time taken to respond, thank you very much.

Answer

Yes, jquery would need to target an existing element to affect it.

in other words, the logic goes: 1. load image asset 2. alter source via 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

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