Q:

How to wait for a website to load the elements's xpath

I would like in my javascript program to be able to start searching for certain elements on a web-page by their xpath.
I want to do that as fast as possible so that means that as soon as the page is loaded I want to locate the element.
I have tried to wait for the DOM of the web-page to be loaded, unofortunately you can only access the id's at that moment and no xpath.
For the moment I am using 
window.onload = function() {
//start searching for element
}

This is very slow especially for websites where there are a lot of images and others because it waits for the full website to be loaded
I would like to know (if it is even possible) how to wait only for the xpath of the elements to be ready and to start searching at that moment.

A:

All the DOM elements are parsed and ready for access when the window.DOMContentLoaded event fires. The load event fires later, after all the external resources have finished downloading.
In the code below, you'll note that Parsed appears before Loaded in the console:

window.addEventListener("DOMContentLoaded", function(){
 console.log("Parsed");
});

window.addEventListener("load", function(){
 console.log("Loaded");
});
<img src="https://cdn.spacetelescope.org/archives/images/large/heic1608a.jpg">

UPDATE:
Based on your comment below, I have put together what your code would look like:

window.addEventListener("DOMContentLoaded", function(){
 // Invoke your custom mouse event function. You need to determine
 // how the element name will be gotten. Here, I am asking the user
 // to supply an element name (div, p, h1, span, etc.)
 setupMouseEvent(prompt("Enter an element name."));
});

function setupMouseEvent(elementName){
  // Locate the first element that matches the name supplied in the parameter
  // Don't use .getElementsByName()[0] to get the first match - 
  // that's very inefficient and uses an outdated API that returns
  // a live node list.  Also, no quotes or concatenation is used here.
  var cb = document.querySelector(elementName);
  
  // The event code below will dispatch a click event for the element
  // but if you don't have a click event handler set up for the element
  // then you won't be able to react to the event.
  cb.addEventListener("click", function(){
    console.log(this.nodeName + " was clicked.");
  });
 
  // While the following does set up a click mouse event,
  // I'm not sure why you are bothering with it. You could just
  // call cb.click() to dispatch the existing click event.
  var event = new MouseEvent('click', { 
    view: window, 
    bubbles: true, 
    cancelable: true 
  });
 
  cb.dispatchEvent(event);
}
<div>Some Element</div>

