1

I'm trying to modify the src of an image for specific pages, like this one: http://oasysgp.kevinmamaqi.com/marina/.

The problem is that the logo changes just after the original one appears. I am using the following code:

jQuery(document).ready(function($){
    /* Cambiar el logotipo para las páginas de CPI */
    if( $('body').hasClass('page-id-18') || $('body').hasClass('page-id-445')) {
        $('#logo').attr("src","/wp-content/uploads/2016/07/oasispci.png");
    }
});

Is possible to load the other image before?

Kevin Mamaqi
  • 267
  • 3
  • 16
  • 3
    Then you need to not show the logo default, and create the img element on fly, and append it to its container. – vaso123 Jul 25 '16 at 13:21
  • 3
    the ready function waits until the page has finished loading before executing the code, hence the delay. If you do not want this to happen, you could try something like this http://stackoverflow.com/questions/12598232/running-jquery-code-before-the-dom-is-ready – Simon Jul 25 '16 at 13:23
  • 1
    Replace the old logo with a spinner, that way it looks okay if the user has to wait for a few seconds if the connection to the image API is slow. – Randy Jul 25 '16 at 13:38

2 Answers2

1

The problem with you code is that you wait for all HTML to load including the img tags, before replacing src.

The easiest way around this is to simply not put an image in src from the server and then start loading on the front-end:

jQuery(document).ready(function() {
  jQuery("img").each(function(i, el) {
    jQuery(el).attr("src", /*Real image here*/ "https://placeholdit.imgix.net/~text?txtsize=60&txt=SO&w=100&h=100");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
<img src="" />
Emil S. Jørgensen
  • 5,684
  • 1
  • 9
  • 22
1

jQuery(document).ready() is always called after dom is loaded.

The best way, implement it in CSS code. by set background in a instead of load in image tag

CSS looks like this

a.logo
{
    background: url('/wp-content/uploads/2016/07/logo-oasis.gif');
    display: inline-block;
    height: 56px !important;
    width: 223px  !important;
    margin-top: 24px  !important;
}

body.page-id-18 a.logo,  body.page-id-445 a.logo
{
    background: url('/wp-content/uploads/2016/07/oasisre.png') !important;
}

Your HTML code for logo part is something like this

<a href="http://oasysgp.kevinmamaqi.com/" class="logo">
</a>
Haresh Vidja
  • 7,750
  • 3
  • 22
  • 40