I have a need to dynamically include and run a script in a page. I am using an image onload event for this:
<img src="blank.gif" onload="DoIt" />
The DoIt function looks like this (just made up this example):
this.onload=' ';this.src='image.jpg';
I have no control on the page itself (I only control the HTML string that the page will call), so I need to include the DoIt function explicitly in the markup.
I tried using an anonymous function, but it didn’t work:
<img src="blank.gif" onload="function(){this.onload=' ';this.src='image.jpg';}" />
Should I just write the script inline, like this:
<img src="blank.gif" onload="this.onload=' ';this.src='image.jpg';" />
And in this case are there any limitations (e.g. script length)?
Thanks for your help!
The
thiswon’t work inside the function since the function is called by thewindowobject, therefore thethiswill refer towindow.If you want to wrap your code inside a function you must wrap that function, call it with the
thisset to the element or pass thethisas a parameter:Yet this doesn’t really make sense to me:
Do you only have control over the img tags? If you can output abritary HTML, then why not just put something in a `script’ tag?
Update
With a script block you could declare your function in there and then simply call it in the onload event.
Now you need only one function for many images.
And if you need to get really fancy, you can setup your script tag to pull in jQuery or any other library.
If you need a lot of these handlers jQuery could do the job.
Still I’m asking my self when you have full control over the HTML why don’t you use a library in the first place? 🙂