Any issues with JS onLoad Event listeners being used in body of document?

I'm creating a script that will open an iframe  container and invoke some pixels. The script can be invoked in the head of the document or in the body. Any potential problems if this JS code is in the body of a document?  Could it cause any issues since it is looking for an event that has already happened or am I misunderstanding this?
        if(window.addEventListener){
            window.addEventListener("load", function() {  document.body.appendChild(iframeTag); }, false);
        } else {
            window.attachEvent("onload", function() {  document.body.appendChild(iframeTag); });
        }

Open in new window


Thanks!
894359Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
I don't see any problems other than style. Makes for a messy document in my view. Clean code implies clean thinking - easier to debug and less prone to errors but from a point of view of whether the code will fire - it will.

Also, unless you are worried about IE 8 then you don't need the check for addeventlistener - it is available in IE9 onwards
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Browser_compatibility
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
894359Author Commented:
Hi Julian, thanks for the feedback as always. I know you are one of the top and best Experts on here and always value your time and responses. I do have a question about part of your response:

"Makes for a messy document in my view. Clean code implies clean thinking"

So what would you recommend if this script can be called in the head or any time after a page loads? This script could potentially be called on some user interaction long after the page has loaded?

Thanks!
0
Julian HansenCommented:
What I meant by that is that in my experience (much of it on this site) errors have been found very easily once the code has been tidied up.

If you are careful about how you layout your code you are more likely to catch errors in the code.

Let's take a look at how JavaScript executes.

The browser will execute JS code as it finds it. However, this can result in a range of outcomes from an immediate write to the document to the attachment of event handlers that will only fire long after the document has loaded.

The head / body placement has long been debated - but really the only real issue is dependencies - if the browser encounters a call to a JavaScript library that has not been loaded (Exacmple: jQuery) it will error out.

There are some benefits to locating the code in the footer - if you locate it higher up it could effect page load which goes to SEO rankings.

Most code is setup to run on document load so that everything the script needs is guaranteed to be there.

The code you are running is effectively this line
 window.addEventListener("load", function() {  document.body.appendChild(iframeTag); }, false);

Open in new window

Which is basically setting up an appendChild after document load - so in this case the only requirement is that it comes after the inclusion of the jQuery library. Other than that it makes no difference - the code will always run at the same time - when the document has completed load - irrespective of where the line is located in your code.

Therefore, it make sense to put it in a place that is logical (head or foot) - but to put it in the middle creates confusion - when you are looking at the page and script is all over the place - much harder to figure out what is going on (that is my personal opinion).
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

894359Author Commented:
Thanks for the clarification Julian! My issue is I won't be able to control when and where the script is invoked. It will be a utility function so it could be called in the head on one page, in the body on the next page and then possibly waiting for some user initiated event to happen on the next.

Take care!
0
894359Author Commented:
Appreciate your responses as always!
0
Julian HansenCommented:
I won't be able to control when and where the script is invoked
This is what I keep trying to explain - it is totally irrelevant when it is invoked (head, body, footer) - in the context of what it does it makes absolutely no difference.

When that code does it adds the anonymous function to an internal list of functions to run when the document is ready. If that code runs in the head - it adds it to the list, if it runs in the body it still just adds it to the list - same for the footer.

The function itself only runs when the document is ready - so it will be the same result irrespective of where that actual snippet is run.

The answer to your question then is - you can put that code anywhere in the document it will have the same effect.

My comment was - if you have the option then locate it at the end of your script - but this is only for aesthetics - in terms of what it does there is no practical advantage for locating it there.
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.