Timing Issues and Javascript
February 01, 2008
Javascript | Web Building

Sometimes, when you use javascript to make a change to some element on a page, you will get a Javascript error along the lines of: "element 'n' has no properties." You check your page, and yes, the element is definitely there, and it is definitely named correctly, and your syntax is definitely correct. So where is the problem?

Well, it may be a timing issue. If your script executes before the element targeted by the script has been rendered, it will not find the element. This can particularly be a problem with frames or iframes. The solution is to move the function call to the bottom of the page, after the element has loaded.


Ads by Google

Posted by ellen at February 01, 2008 12:14 PM


For example, in this test page, a script detects a parameter in the query string ("tp=javascript") and loads the corresponding topic page into an iframe. Or at least it is supposed to. What actually happens is that the default page remains loaded, and a javascript error occurs:

When the script is working, the list of articles loaded into the iframe should be titled "Javascript". When it is NOT working the list will be the default page that gets loaded even if javascript is not running: "Most Popular."

If you view the source of the page, you'll notice that the call to the swapContent() function is above the iFrame.

...snipped...
function swapContent(path){document.getElementById('contentFrame').src=("http://thedesignspace.net/MT2archives/"+path+"/index.html");}
  var gtopic= qsParm['tp'];
  if (gtopic!= null){swapContent(gtopic)}
  </script>
  </head>
  <div id="main">
  <table width="100%" height="900" border="0" >
  <tr valign="top">
  <td id="midCol" style="text-align:left;padding-left:24px;">

<iframe id="contentFrame" name="contentFrame" src="http://thedesignspace.net/MT2archives/_most_popular/" scrolling="no" width="400" height="1200" frameborder="1"></iframe></td>
</tr>

...snipped...

If the call to the function is moved to the end of the page, the script starts working. The iFrame will be loaded with the page corresponding to "tp=javascript" (topic=javascript).

Click here to try it.


If you are working on a frameset page, however, browsers will not recognize scripts down below the frameset tag.

However there is another way to get around the timing issue: tell the script to wait until everything has loaded before executing.


function changeframeSrc(){ 
     if(frames[0]){//alert('yes');
	 frames[0].location='page03.htm';}
     else{setTimeout("changeframeSrc()",100);}
      }


changeframeSrc();


Ads by Google


Ads by Google

 RSS   |   Contact Me


Ads by Google