andrew makes things

a blog about programming, machine learning, and whatever else I'm working on

Replacement for Script Onload in IE

| Comments

This is an old post from my last blog.

Firefox and Safari support an onload event for SCRIPT elements. That is, you can dynamically add a new script to a page, set its onload event to fire a callback, and know when the script has been successfully loaded. You would want to do this because when you include a bunch of new SCRIPT tags in a page, there are no guarantees in what order the browser will decide to evaluate them, thus making dependencies among the scripts difficult to resolve. Using onload to chain the script additions is one solution to this, however, Internet Explorer doesn’t seem to support onload in SCRIPT tags.

Update: Owen in the comments says: Thanks for your post, but I have since found a more efficient way to do this and thought I might share with you. As you said you can use an onload event in Firefox, but in IE you can use the onreadystatechange event. Works from at least IE6. Haven’t tested earlier.

My solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
function importJS(src, look_for, onload) {

   var s = document.createElement('script');

   s.setAttribute('type', 'text/javascript');

   s.setAttribute('src', src);

   if (onload) wait_for_script_load(look_for, onload);

   var head = document.getElementsByTagName('head')[0];

   if (head) {

     head.appendChild(s);

   } else {

     document.body.appendChild(s);

   }

 }



 function importCSS(href, look_for, onload) {

   var s = document.createElement('link');

   s.setAttribute('rel', 'stylesheet');

   s.setAttribute('type', 'text/css');

   s.setAttribute('media', 'screen');

   s.setAttribute('href', href);

   if (onload) wait_for_script_load(look_for, onload);

   var head = document.getElementsByTagName('head')[0];

   if (head) {

     head.appendChild(s);

   } else {

     document.body.appendChild(s);

   }

 }



 function wait_for_script_load(look_for, callback) {

   var interval = setInterval(function() {

     if (eval("typeof " + look_for) != 'undefined') {

       clearInterval(interval);

       callback();

     }

   }, 50);

 }



 (function(){

   importCSS('some_stylesheet.css');

   importJS('jquery-1.2.6.js', 'jQuery', function() {

     importJS('some_script_that_uses_jquery.js');

     importJS('another_one.js', 'SomeClassOrVariableSetByTheScript',

       function() {

         importJS('a_script_that_uses_that_class_or_variable.js');

       });

   });

 })();

Comments