tags:

views:

45

answers:

3

For a website I'm working on, I've created an embed function. This is just a call to a javascript on my server that injects some HTML on the remote server.

To make sure the embeds also get some Google juice, I've added a piece of html, so the embed code looks something like this:

<script type="text/javascript" src="http://myserver.com/myscript.js"&gt;&lt;/script&gt;
<div id="embedSource">Source: <a href="myserver.com">mysite.com</a></div>

It's easy to remove the last div with the source in it from the embed code. So I thought I'd just add a little detection script in the first "myscript.js" to detect the presence of the div with id "embedSource".

Problem is: the javascript is always executed first, then the div is being added to the DOM and there is no way that I can add the embedSource div first.

I've tried to check using:

window.onload = CheckIfEmbedCodeIsComplete();

But this event is fired to early (Chrome, FF and IE). Even though for most browsers it should be enouugh (right?). Also tried:

setTimeOut(CheckIfEmbedCodeIsComplete(), 5000);

But again, the check is being called immediately, not after 5 seconds as you would expect.

What can I do to still check if that div exists?

+1  A: 

You need to write an onload-function in order to execute your script. A solution can be found here.

I don't know if that matters, but if you plan to embed multiple objects into a site, you need to use classes. (Multiple elements with the same id aren't possible.)

FB55
Thanks, I should've added that I did try something similar, question updated! Yes, I have something in place to add unique ID's, thanks!
sebastiaan
A: 

Move your script out of the head and just before the end </body> tag.

<body>
   <div id="embedSource">Source: <a href="myserver.com">mysite.com</a></div>
   ...
   ...
   <script type="text/javascript" src="http://myserver.com/myscript.js"&gt;&lt;/script&gt;
</body>

The page will load quicker, and the DOM will load so you'll have access to the elements.

Steve Hansell
Sorry, not possible as stated in the original question.
sebastiaan
A: 

To answer my own question, I had to change the timeout call to this:

setTimeout('CheckIfEmbedCodeIsComplete()', 5000);
sebastiaan