FlyC
FlyC

Reputation: 1874

Javascript: Set eventListener to DOM object without window.onload?

My index.html include two javascript codes which are plugin.js and main.js(main include after plugin),
I want to make plugin.js as a reusable plugin, like checking if the index.html file has any elements which have click-me class attribute, if index.html has this kind of elements, then set every this kind of elements an eventListener.

I want my window.onload function ALWAYS in main.js rather than plugin.js, but in this case I cant' get DOM object by className in plugin.js, I also don't want to call any function of plugin.js in main.js.

Does anyone ahs any idea?

Upvotes: 0

Views: 944

Answers (3)

Tiago Engel
Tiago Engel

Reputation: 3663

You can just include the scripts after the body.

<body>
</body>
<!-- add your scripts here -->

Then you don't need to check if the document is ready anymore, this has the drawback of only starting the download after the page is fully rendered.

Another possibility is using defer

<script type="text/javascript" src="plugin.js" defer></script>
<script type="text/javascript" src="main.js" defer></script>

This way scripts are downloaded as soon as possible but are executed only after the page is ready, and in order.

A more detailed answer here

Upvotes: 2

Tom&#225;š Zato
Tom&#225;š Zato

Reputation: 53129

Well, you should properly use onload as an event listener:

window.addEventListener("load", function() {

});

This can be added as many times as you wish, both in main.js and plugin.js.

Additionally, it's better to use DOMContentLoaded event, because it doesn't wait on loading images. That's really important, if you rely on window.onload, just one pending image can make your page useless for first 10 seconds of the visit. It's used like this:

  document.addEventListener("DOMContentLoaded", function(event) {
    console.log("DOM fully loaded and parsed");
  });

It has compatibility issues however, so I recommend using some library.

Oh and last thing - don't link your scripts before body unless needed. They block parsing of the page.

Upvotes: 1

Kulvar
Kulvar

Reputation: 1179

Why don't you just check if the clicked element have the click-me class from the root? It makes you declare only one listener on the body.

function listener(event) {
    if(event.target.classList.contains("click-me")) {
        // Do something
    }
}
document.body.addEventListener("click", listener, true);

Upvotes: -1

Related Questions