0

I'm building a site and I have loads of scripts going on there, theyre all contained in different files and some of them are onload functions. I know about using a function to run all of them. However this doesn't work so well with multiple files. I've tried using an onload.js file:

window.onload = function() {
    // Site wide funcs
    searchShow();
    // Page specific
    if(getProducts && loadMore){
        getProducts();
        loadMore();
    }
    if(checkBox){
        checkBox();
    }
    if(styleProduct) {
        styleProduct();
    }

}

where it should check if the function exists on the page before running it. (Some files are referenced in each file some are site wide and are referenced in the header file) Could anyone suggest a better option for having all these onload files?

1 Answer 1

1

In your script files stick to addEventListener or attachEvent, as both allow multiple handlers for single event.

EDIT

As these two functions are browser specific, it is a good idea to start with some kind of wrapper:

function createEvent(objectTarget, eventName, eventHandler)
{
    if (objectTarget.addEventListener)
        objectTarget.addEventListener(eventName,eventHandler,false);
    else if (objectTarget.attachEvent)
        objectTarget.attachEvent('on'+eventName,genericHandler);
}

Now use createEvent to attach new handler to specific event.

createEvent(window, 'load', handler1);
createEvent(window, 'load', handler2);
...

Please take into account, that there are more severe differences in event model between browser (such as where is event object or target vs. srcElement).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! :) How do I use attach event?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.