Change Language


Follow Navioo On Twitter

Alternate Ajax Techniques Part 1 -Using HTML: iframe



IFRAME


1.Dynamic content loading in iFrame

HTML: iframe

The concept is simple: create a new <iframe/> element and assign a valid url to its src attribute to load html content that isn't initially written into the page.

All you need to do is create a <iframe/> element using the DOM createElement() method and add it to the page:

var oIframe = document.createElement("iframe");
oIframe.src = "/path/to/my.html";
oIframe.id = "myUnicId";
oIframe.name = "myIframeName";
document.body.appendChild(oIframe);

Instead, you'll need to have a trigger ( a callback function ) that is the executed at the end of loading HTML file(my.html).

1.1 Simple Example ( Example 1)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Example 1</title>
    <script type="text/javascript">//<![CDATA[
        function makeRequest() {
          var oIframe = document.createElement("iframe");
          document.body.appendChild(oIframe);
          oIframe.src = "/path/to/my.html";
          oIframe.id = "myUnicId";
          oIframe.name = "myIframeName";
          if(window.ActiveXObject){
                    oIframe.attachEvent('onload',callback);
          }else{
                    oIframe.addEventListener('load',callback,false);
          }
        }

        function callback() {
          var oIframe = document.getElementById("myUnicId");
          var oDoc = oIframe.contentWindow || oIframe.contentDocument;
          if (oDoc.document) {
             oDoc = oDoc.document;
          }
          sText=oDoc.body.innerHTML;
          alert("Loaded from file: " + sText);
        }
    //]]>
    </script>
  </head>
  <body>
    <input type="button" value="Click Me" onclick="makeRequest()" />
  </body>
</html>

The HTML file my.html contains a single line:

<body>Hello world!<body/>

 

DEMO of Example 1

 


Other Techniques
- Loading XML
- Dynamic Script Loading
- Images and Cookies

Ajax Javascript feed

↑ Grab this Headline Animator