Question

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)

Was it helpful?

Solution

I am afraid that if you can't use jQuery or some other library you need to reproduce a way good deal of their functionality. The reason is that browsers handle the onLoad event differently.

I recommend that you download jQuery's code and see how the documentready function is implemented.

OTHER TIPS

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.

The onLoad event is supposed to be run when the element it is attached to is loaded. But some browsers* misinpret this as "beforeload" or "sometime during load" so the safest option to be sure something is run after all html is loaded, is to add a call to the function on the bottom of the HTML source, like this:

    ...
        <script type="text/javascript">
            c_onload();
        </script>
    </body>
</html>

(* at least some versions of Safari for Windows I do beleave have this issue)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top