Anirudhan J
Anirudhan J

Reputation: 2072

Create iframe only using javascript

I am working on a slideshow implementation. We have to prefetch images for better user experience. Currently I am using hidden img tags to trigger the image load. But when a user moves say from 1st image to 80th image, the prefetch image request started for the first image doesn't get cancelled.

Using iframes we can call stop() on iframe object to stop loading the previous set of images. The norm for creating iframes using javascript appears to be

ifrm = document.createElement("IFRAME");

I dont want to do that as I dont want my iframes to be appended to DOM. There is a HTMLFrameElement. But I am not sure how to use it.

So my question is, how to create iframes in javascript without accessing document object.

Upvotes: 0

Views: 161

Answers (2)

Teemu
Teemu

Reputation: 23416

Yes, you can create an iframe to the document without appending it, but the accessibility is limited to the iframe element itself.

  • Unappended elements have not parentElement nor parentNode
  • If you'd lose the reference to iframe (ifrm in your example), the element is gone forever
  • You can't access the window within the iframe or the loaded document
  • onload event of the iframe is not fired

You can change for example src or size of an unappended iframe. And yes, the content is loaded asynchronously related to the main page.

Upvotes: 2

joews
joews

Reputation: 30340

The code you posted is the solution.

You cannot write equivalent code without using document (and why would you want to?). You need to use Javascript's interface to the DOM, which is provided through document (or window).

You can use jQuery and other DOM-aware libraries to abstract away the DOM API calls, but under the covers they all call document methods.

Upvotes: 3

Related Questions