Paul Paul - 10 days ago 6
HTML Question

.append() very slow to attach image to transition

I am having a problem with an image not loading fast enough on mobile.
My project has an image and a button. When the button is clicked, the image slides downwards and another image slides from the top to replace it. Here is the code

html

<div class="main">

<div id="myDiv1><img src="img1.jpg" width="100%"></div>
<div id="myDiv2"></div>

</div>


css

.moveFromTop {
animation: moveFromTop 2s ease both;
}

.moveToBottom {
animation: moveToBottom 2s ease both;
}

@keyframes moveFromTop {
from { transform: translateY(-100%); }
}

@keyframes moveToBottom {
from { }
to { transform: translateY(100%); }
}


js

var img2 = new Image();

img2.src = "img2.jpg";

$(img2).css("width","100%");

$(document).ready( function () {


$('#button').click(function(){

$('#myDiv1').addClass('moveToBottom');

$("#myDiv2").append(img2);

$('#myDiv2').addClass('moveFromTop');
});
});


It's fairly straightforward and it works on desktop. On mobile though, the second image doesn't load immediately as you click the #button so you get a black image for a second which completely ruins the effect I am going for. This happens both on iPhone and iPad. I haven't had the chance to test on android yet, but you would have thought at $700+ apple phone could deal with a little transition ;) I am wondering if there is something I am doing wrong with my code that is creating this issue. This is my first project. Thanks for your time.

-------------------------------------------------------------------edit------------------------------------------------------------

I have tried quite a few things since I posted this question. I've tried moving the "append" line to outside of the "click" function, and the image loads immediately, pointing to this problem not having anything to do with the append() method. I have also tried a different approach, by having the image load immediately with display "none" and then doing a .css("display","block") instead of append. Still we get the black image that ruins the effect I am going for on mobile.
If you want to see the problem for yourselves, please visit "alicesoyer.com". The site is live but under construction. You need to click anywhere on the screen to fire up the animation. You will see the effect I am going for. On desktop it works fine. On mobile it does not. I am testing on an iPad air and iPhone6. Thanks.

Answer

The solution is to add

    * {
        -webkit-transform: translate3d(0,0,0);
    }

or at least to some child elements to trigger the browser to use hardware accelaration better. More info at this page