Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Robert Manolis
STAFF
Robert Manolis
Treehouse Guest Teacher

Will inserting background images with JavaScript instead of CSS, help or hurt a site's speed and performance?

In an attempt to get the page loading as fast as possible, I've been using JavaScript instead of CSS to insert background images. Is this a good idea?

2 Answers

It probably does not hurt your site performance, unless you do something strange :P

You can actually use JS to dynamically load images in ways that improve a website's perceived performance. For instance, you could select smaller images to download for smaller devices, or only load an image when a user scrolls far enough down the page, or clicks a button, etc...

One thing to keep in mind is that JS is not going to enabled for 100% of users, and search engines may not be able to read you content (this should not matter in the case of background images though) So make sure that you are still offering some version of your content in those situations if you are able.

Tomas Pavlik
Tomas Pavlik
26,726 Points

Hi Robert, generally, it is not a mistake to add styles with javascript, but... always keep in mind that HTML is for content, CSS for styling your page and Javascript is for behavior. So you shouldn't use javascript for styling, use CSS. Your code will me more readable and easier to maintain.

Tom