John Smith
John Smith

Reputation: 6207

Responsive design based on jQuery - changing elements, unwanted preloads

<img id="banner_desktop" src="http://hdwallpaper2013.com/wp-content/uploads/2013/02/Space-Background-Images-HD-Wallpaper-1080x607.jpg" />
<img id="banner_phone" src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQgcQd5s4R1KaQAQM6qJ3cUtEb2sdWjNGOOfzzdEt3mMx0TAGqZ" />
Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content Site content

#banner_desktop
{
    width: 100%;
}

#banner_phone
{
    width: 100%;
}

$( window ).resize(function() {
    if ($('body').width() < 300)
    {
        $('#banner_desktop').hide();
        $('#banner_phone').show();
    }
    else
    {
        $('#banner_desktop').show();
        $('#banner_phone').hide();
    }
});

$( document ).ready(function() {
    $(window).trigger('resize');
});

http://jsfiddle.net/j9jnq/

I have a "special" attitude toward responsive design this time. Here, the banner image changes according to the width. But in this case, both image preloads, when youre on desktop, the 2nd image shouldnt need to load - on phones, the 1st one shouldnt. Its not only unnecceserly, it also disturbs a view, because something shows and disappears. But I cant do the showing-hiding before the HTML loads. I know there is mediaquery, but its impossible to do it for every elements (I will do this kind of approach with different sizes).

Upvotes: 0

Views: 69

Answers (1)

Shomz
Shomz

Reputation: 37701

You can either hide them both by CSS, and then when JS kicks in, decide which to show or, strongly suggested, is to revisit media queries. In the long run, you'll end up doing much more work and getting much less performance if you go with JS.

In fact, your code right now is harder to maintain, longer and less performing than a potential media query version doing the same thing.

Upvotes: 2

Related Questions