Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of onload handler and src set important in a script element?

Coming from this answer that says:

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/

I am skeptical about believing that this would be the correct answer to the question.

So, is the order of setting onload handler and src so important? I think they are evaluated by browser instantly so I think that there is no difference between:

el.onload = function() { //...
el.src = script;

and

el.src = script;
el.onload = function() { //...

Am I right?

like image 688
Ionică Bizău Avatar asked Jan 19 '14 08:01

Ionică Bizău


2 Answers

Is 'el' already part of your live DOM? If so, when you change its onload event handler, it's contents will not be evaluated (because the load event already occurred).

el.onload = function() { //...

If el is not already added to the page, for instance if you're building a view, and will be injected into the page when everything is set, then yes it's load event will be fired when it's added to the page.

Be cautious about what might in the 'src' might depend on what happened in 'onload'.

like image 94
thinkbigthinksmall Avatar answered Oct 20 '22 17:10

thinkbigthinksmall


@thinkbigthinksmall is right.

I would add that this behavior is webkit specific, Firefox will queue the event handler, so in this case it wouldn't matter.

I am not sure what the specs do say about it, but IMM FF behavior is the correct one.

Anyway, since webkit behaves like that, one should always set the src after the onload event has been declared, otherwise, cached media will fire the onload event before your script has been parsed.

One workaround though is to set your src again after the onload event has been declared :

<img src="someCachedMedia.ext" id="img"/>
<script>
  img.onload = doStuff;
  img.src = img.src; // force the onload to fire again
</script>

This way, you're sure the onload event will fire. Also, a single request should be made, since the first one will be cached.

like image 27
Kaiido Avatar answered Oct 20 '22 19:10

Kaiido