bruh
bruh

Reputation: 2305

Create element in HTML vs Javascript

The purpose - an image gallery.

As opposed to creating each gallery-image inside a 'gallery' div, like below:

<div id="html_collection">
  <img src="picture_1">
  <img src="picture_2">
  <img src="picture_3">
</div>

I'm storing them inside a javascript array object - for simplicity, like below:

var js_collection = [
    {
      'gallery' : 'picture_1.jpg',
    },
    {
      'gallery' : 'picture_2.jpg',
    },
    {
      'gallery' : 'picture_3.jpg'
    }

From there I will create an empty <div id="carousel"></div> inside the HTML file and append each 'gallery' image into it dynamically through JS, by clicking 'next' and 'previous' buttons. These buttons will cycle through the js_collection array.

For example:

function showCarousel(x) {
    var slide     = document.createElement('img')
    slide.src     = js_collection[x].gallery
    var output    = carousel.appendChild(slide)
}

The concern - I feel like redrawing the img node and fetching the current img from the JS collection everytime we hit next or previous.. may be dirty in a way. I know the same result can be achieved by showing and hiding imgs in the first 'html_collection' option - but I prefer the flexibility of the second implementation. Can I get away with it, or is this just wrong?


EDIT: I went with Leeish's suggestion and created a div like so,

<div id='carousel'>
    <img id='carousel_slide' src='nameOfFirstSlideHere.jpg'>
</div>

From there, I dynamically switched the img 'SRC' rather in redraw the 'IMG' itself each time. Cheers

Upvotes: 0

Views: 72

Answers (1)

DLH
DLH

Reputation: 565

My concern about your script approach is that the user may experience a noticeable delay upon every click of the next/previous button while waiting for the next image to be retrieved, at least as your script is currently written. On the other hand, if the number of images is large, there would be a significant up-front delay in the HTML version as you waited for the entire group of images to load.

I think the best solution would be one that preloaded at least enough images to make sure that when the user clicks the button, the next or previous images is (at least usually) already loaded so the only delay is the tiny one to append the content. If your images are small, you might consider using CSS sprites to load several images at once and cut down on the number of HTTP requests, though this would require a bit more coding.

The other option, which is simpler to code, but doesn't reduce the number of image requests, would be have your showCarousel method create an image object, load the src, and append to the carousel for image x + 1, but hide that image x + 1 initially and show image x. That way, assuming the user spent a few seconds looking at each image, the user should see image x essentially immediately, while x + 1 gets ready just in case the user asks for it.

Upvotes: 1

Related Questions