I am adding <script/> tags from javascript to load some libraries (e.g. jquery). When all the libraries load, I run the main code. To wait until everything is ready, I use a solution similar to the one that was in this answer (found on the Internet).
Now the story: http://jsfiddle.net/EH84z/
function load_javascript(src) { var a = document.createElement('script'); a.type = 'text/javascript'; a.src = src; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(a, s); } load_javascript('http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js'); function addEvent(elm, evType, fn, useCapture) { //Credit: Function written by Scott Andrews //(slightly modified) var ret = 0; if (elm.addEventListener) { ret = elm.addEventListener(evType, fn, useCapture); } else if (elm.attachEvent) { ret = elm.attachEvent('on' + evType, fn); } else { elm['on' + evType] = fn; } return ret; } addEvent(window, "load", function() { console.log(window.jQuery + ' ' + window.$); $(document); }, false);
It works fine in Firefox, but often fails in Chrome. Every second time I press the jsfiddle "run" button, the callback is executed before the jQuery loads, which gives an error in the Chrome console.
addEventListener this mean that I am abusing addEventListener ? If so, what is the correct use for it and how can I wait for all scripts to load?
Thank!
PS I have not tested it yet in other browsers, so please comment if it does not work somewhere else.
change
if I wait one second (using setTimout ) before testing, the success rate increases to 100%. Example http://jsfiddle.net/EH84z/1/
javascript jquery google-chrome onload
Nikita Rybak Oct 08 '10 at 9:14 2010-10-08 09:14
source share