Fer
Fer

Reputation: 4196

Does dynamically prefetching a resource using DOM injection work or make sense?

This is largely a theoretical question, for which I do have a practical purpose. I first am looking for some conceptual answers before diving into practice, as perhaps the idea itself does not make sense.

Imagine a slideshow that is entirely javascript-based. Users see a large image on their screen and click to move to the next large image. Upon clicking, the next image is loaded and inserted into the DOM, replacing the previous one.

I recently learned that prefetching directives can help in speeding up the loading of resources that are very likely to be used next. Note that I said resources, not pages. The slideshow is a single page.

In an image slideshow, it is very obvious that it is likely that the next image is needed, thus if image1 is on screen, I could dynamically add this to the DOM:

<link rel="prefetch" href="http://img.mysite.com/img2.jpg">

My questions regarding this idea:

I did a lot of searching but I am unable to find answers on this specific situation of dynamically injected prefetch hints.

Upvotes: 5

Views: 1880

Answers (1)

Alexander Gessler
Alexander Gessler

Reputation: 46607

onload always gets triggered, even if the image is coming from cache. You do not have to worry about timing effects or race conditions, any such behavior would be a browser bug.

As mentioned in comments, rel=prefetch is not the only way of achieving pre-fetching. It works though even when dynamically inserted into the DOM. After all, you could fetch the image without the prefetch attribute and hide it.

Upvotes: 4

Related Questions