Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onload from external js file

I'm writing a js script that people will add to their web site by adding a single line of code to the header or end of the body part of their HTML.

My question is how to do the onload right on the external js file. Will the code below work? Can't it possibly run after the onload of the document and miss the onload event?

function c_onload () {  alert ('onload'); }

if (window.attachEvent) {window.attachEvent('onload', c_onload);}
else if (window.addEventListener) {window.addEventListener('load', c_onload, false);}
else {document.addEventListener('load', c_onload, false);} 

(I can't use Jquery or any other library)

like image 661
Nir Avatar asked May 13 '26 06:05

Nir


1 Answers

What is your last else-clause

else {document.addEventListener('load', c_onload, false);

for? It's rather useless, imho.

The following should be a cross-browser solution: It first checks for addEventListener(), then attachEvent() and falls back to onload = ...

function chain(f1, f2) {
    return typeof f1 !== 'function' ? f2 : function() {
        var r1 = f1.apply(this, arguments),
            r2 = f2.apply(this, arguments);
        return typeof r1 === 'undefined' ? r2 : (r1 && r2);
    };
}

function addOnloadListener(func) {
    if(window.addEventListener) 
        window.addEventListener('load', func, false);
    else if(window.attachEvent)
        window.attachEvent('onload', func);
    else window.onload = chain(window.onload, func);
}

Also, what kgiannakakis stated

The reason is that browsers handle the onLoad event differently.

is not true: all major browsers handle window.onload the same way, ie the listener function gets executed after the external resources - including your external script - have been loaded. The problem lies with DOMContentLoaded - that's where the hacks with doScroll(), defer, onreadystatechange and whatever else someone has cooked up come to play.


Depending on your target audience, you may either want to drop the fallback code or even use it exclusively. My vote would go for dropping it.

like image 122
Christoph Avatar answered May 14 '26 18:05

Christoph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!