onload' handler for 'script' tag in internet explorer
You should call jQuery.getScript
, which does exactly what you're looking for.
EDIT: Here is the relevant source code from jQuery:
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Handle Script loading
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState ||
this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
jQuery.handleSuccess( s, xhr, status, data );
jQuery.handleComplete( s, xhr, status, data );
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
Trying to fire the onload event on script tag
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
img onload doesn't work well in IE7
IE7 is trying to resize the image before the DOM tree is fully rendered. You need to run it on document.onload... you'll just need to make sure your function can handle being passed a reference to the element that isn't "this."
Alternatively... and I hope this isn't a flameable offense... jQuery makes stuff like this really, really easy.
EDIT in response to EDIT 1:
You can put document.onload(runFunction);
in any script tag, anywhere in the body. it will still wait until the document is loaded to run the function.
What happened when a script tag is encountered within a html file?
This is described in HTML5 CR, in the section on the script
element. In the example case, since neither the defer
nor the async
attribute is used, the browser will fetch (with a GET request) and execute the script before continuing the processing of the HTML document. The default handling is thus synchronous blocking behavior.
However, if you really use markup like <script src="http://...example.js"/>
without an end tag </script>
, the script is not fetched at all, except in the rare case where you serve the HTML document with an XML content type. The reason is that <script src="http://...example.js"/>
is parsed as a start tag only, so all the rest is parsed as content of a script
element, and when no end tag is parsed, the script
element is not completed. So don’t try to use “self-closing” syntax; instead, write <script src="http://...example.js"></script>
.
How to trigger script.onerror in Internet Explorer?
I found this buried in some MSDN documentation:
Note that the documentation mistakenly says this works for elements too; the error will be fixed in the Workshop documentation for the final release of Internet Explorer 5 in March.
The next thing I thought of that could help is the onreadystatechange event:
<script src="http://www.google.com/NOTFOUND.js" onreadystatechange="alert(this.readyState)">
This event fires twice for me, once with "loading" and again with "loaded", whether the script is valid or not. Other documentation I've found says that sometimes it fires a complete event, and it's not really clear when it's supposed to fire. So it looks like that won't work.
So I think you're left with the hacky solution of checking that a variable which the script is supposed to declare really exists. In HTML:
<script src="http://yourdomain.com/declare_foo.js"></script>
<script>if (typeof foo == "undefined") {alert ('error loading script');}</script>
And then of course in declare_foo.js, you'd have
var foo = 'Script loaded successfully';
Script does not run on IE after deferring parsing of javascript
All the script loaders I've seen append the script element to the first head tag, not the body tag like is shown in this description.
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://connect.facebook.net/en_US/all.js#xfbml=1';
head.appendChild(script);
I can't say if that is what is causing your issue on IE, but it seems worth changing to.
Also, since you're waiting for the window load event, do you realize that this script won't be loaded until the last image on the page has finished downloading. That's a lot longer than you have to wait.
As best I can tell, IE just doesn't work if the FB script is loaded after the content is loaded. Even if you put it after the content in a traditional script tag, it doesn't work in IE. It must be something about the way the facebook script works in IE. I'm sorry I can't help more. You can see that even that this doesn't work in IE8:
<div id="fb-root"></div><fb:like-box href="http://facebook.com/pages/MyJobMag/165211540158300" width="336" show_faces="false" stream="false" header="true" colorscheme="light"></fb:like-box>
<script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script>
But, this does work in IE8:
P.S. You have an extraneous semicolon in your HTML after the URL, but removing it doesn't seem to solve the problem.
Javascript onload and script callback functions, which takes the precedence?
Will that json_callback function always have precedence before the onload handler?
If the external script calls my_callback
synchronously then yes.
The scripting
section in the official html5 specification describes how these things are supposed to work. The specification is quite general and has to deal with a lot of details conserning encoding, CORS, ignore-destructive-writes counter
and so on. But for this question we don't care about these specifics.
In step 4 there is a note:
Note: This is where the script is compiled and actually executed.
And in step 7 the load
event is fired:
fire a simple event named load at the script element.
So the specification defines that the load
event is always fired after the script has been executed.
As you see the specification also tells us why the onerror
event is not fired if you change the URL. The error
event is only created if loading the script fails. But all requests to https://api.clicky.com/api/stats/
return a HTTP 200 status. The invalid URLs return XML and thus a SyntaxError is thrown. But this does not cause the onerror
handler to be triggered.
As others have mentioned if the callback is called asynchronously they can call your callback after the onload
event. But I don't see a reason why they would do this async in your external script.
Related Topics
Why Should I Use a Semicolon After Every Function in JavaScript
Remove Not Alphanumeric Characters from String
Coordinating Parallel Execution in Node.Js
Best Way to Get the Key of a Key/Value JavaScript Object
Serializing Object That Contains Cyclic Object Value
How to Overload Functions in JavaScript
Load Jquery with JavaScript and Use Jquery
Preventdefault() on an <A> Tag
JavaScript Print Iframe Contents Only
How to Dynamically Insert a <Script> Tag via Jquery After Page Load
Call Multiple Functions Onclick Reactjs
Getting the Return Value of JavaScript Code in Selenium
JavaScript Sleep/Wait Before Continuing
Window.Localstorage VS Chrome.Storage.Local
How to Check If an Element Is Really Visible with JavaScript