Need to fire onload event on script element?
I've recently had a client request to have a "desktop quote" page that used a third party API to get stock quote information in a popup. The interesting thing about the API is to access the data you modified the src of a script tag so it would return javascript that created an object that you could use to access the stock quote data.
I have a dropdown list of possible comparison quotes to be loaded dynamically. I attach an onchange event handler to it so I can refresh the page with the appropriate query string (need to refresh page every 15 minutes to get latest data). Here is where I add the event handler.
dojo.query("#bench").connect("onchange", this, function(e) {
var url = getUrl();
if(url != null)
window.location = url + "?ticker=" + e.target.value;
});
On page load using dojo.addOnLoad(), I call the below code if there is a query string parameter named ticker and the value is valid. This snippet adds a script tag to the DOM under the body tag. Then attaches an onload event to the script element.
var n = dojo.create("script", {
type: "text/javascript",
src: "http://apps.shareholder.com/irxml/irxml.aspx?COMPANYID=abc&PIN=abc123&FUNCTION=StockQuote&OUTPUT=js2&TICKER=" + ticker
}, dojo.body(), "first")
if (dojo.isIE)
dojo.query(n).connect("onreadystatechange", this, function() {
populateData("Comp");
});
else
dojo.query(n).connect("onload", this, function() {
populateData("Comp");
});
Notice the if(dojo.isIE)? The onload event is not fired in IE for the script element (works fine in firefox and chrome). However, the onreadystatechange event is. This ensures that the objects/code in the the dynamically injected javascript gets executed before the populateData function is called.
May 30th, 2011 - 07:01
Thank you Victor. This proved very helpful to trigger a script inside an external page, that gets loaded into a dijit.dialog at runtime (from a call to dojo/connect without an event specified).