1

In javascript, I am inserting a <script tag> into an iframe like this:

var iframe = document.getElementById('iframe');
var doc= iframe.contentWindow.document.getElementsByTagName('head')[0];

var jquery = document.createElement("script");
jquery.type = "text/javascript";
jquery.src   = "jquery-1.9.1.min.js";

var script   = document.createElement("script");
script.type  = "text/javascript";
script.src   = "blah.js";

doc.appendChild(jquery);
doc.appendChild(script);

However, there is jquery code in the blah.js, and sometimes this script fails because the jquery script didn't finish loading yet. Is there a way to wait until it finished loading?

Thanks.

omega
  • 40,311
  • 81
  • 251
  • 474
  • `script.onready = function () { ... }` (or being a cool guy and using addEventListener/attachEvent) I suppose – Ven May 23 '13 at 17:10
  • do you mean `jquery.onready = function () { ... }` and then in the function, I load the `script` variable? – omega May 23 '13 at 17:12
  • I tried this `jquery.onready = function() { alert(1); }` but the alert never happened. – omega May 23 '13 at 17:18
  • 3
    actually, its `onload` not `onready`.... – omega May 23 '13 at 17:22

2 Answers2

3

The key is to use script.onload = functionName; with a fix for IE8. See https://stackoverflow.com/a/15437678/2227298 for the complete code.

Once jQuery is loaded, you can use jQuery.getScript with the success parameter.

Community
  • 1
  • 1
KrisWebDev
  • 9,342
  • 4
  • 39
  • 59
1

Add a callback at the end of the first script.

at the end of jquery.js:

if (window.jqueryLoaded)
    window.jqueryLoaded();

in your code:

// create the function that will be called once jquery finishes loading
function jqueryLoaded()
{
    doc.appendChild(blah);
}

// load jquery
doc.appendChild(jquery);

Alternative (not really recommended) way by using a timer if you can't modify the jquery.js file:

var checkjQuery = window.setInterval(function() {
    if (!window.jQuery)
        return;
    window.clearInterval(checkjQuery);

    window.jqueryLoaded();
}, 10);
Knaģis
  • 20,827
  • 7
  • 66
  • 80