c_harrris
c_harrris

Reputation: 1

Improve JavaScript Speed

My website, www.runthisday.com, has JavaScript that pulls an about page to 50% of the width of the user's screen, while pushing other components to the left to make room for the about page.

The problem is that when the user clicks the about button for the first time, this JavaScript is extremely slow because Chrome waits for the images to load. For other web browser, the JavaScript is quick, but the images take a second to load. After the first use of the button, the about slide works fine. But it is the first time that really matters.

Is there a way to fix this so that the JavaScript works quickly and the images appear immediately when the button is clicked? Would directing the users to a loading page fix this? If so, can you direct me to somewhere that would show me how I can use JavaScript to load the site in that way.

I really appreciate the help.

Upvotes: 0

Views: 77

Answers (2)

efsandino
efsandino

Reputation: 975

If the images are always the same, probably you can store in web cache... for ever... In order to just wait the first time...

Other option is not to load big images, probably you can use some repetitive titled images... in some places and really when needed load images...

Upvotes: 0

Mulan
Mulan

Reputation: 135415

Your images are huge. So start by resizing those to a much more manageable size.

But another thing you can do is preload your images. Here's a simple wrapper that you can use to load some images and know when they're ready.

// Url -> Promise<ImageElement>
var image = function(src) {
  return new Promise(function(pass, fail) {
    var i = new Image()
    i.src = src
    i.onload = event=> pass(i)
  })
}
    
var url = "http://www.runthisday.com/img/the_hammer.jpg"
image(url).then(elem => document.body.appendChild(elem))

You could even use a Promise.all wrapper to ensure multiple images have loaded for a particular section

Promise.all([
  image('one.jpg'),
  image('two.jpg'),
  image('three.jpg')
]).then(images => console.log("all images loaded", images)

Upvotes: 4

Related Questions