It's a bad idea to use the document when it's not fully loaded. Depending on the time it takes to load it, your values are going to be different. That's why you get different behaviors.
To solve this, just wait for the document to be loaded by wrapping your code like this:window.addEventListener('load', function(){ /* ...YOUR CODE GOES HERE... */ });
When you load a page, 2 main events are fired: DOMContentLoaded, when the DOM is ready (All the HTML is loaded). Then, a load event fires when all external resources (CSS, images) are loaded. Using defer waits for the first event to fire, but not the other one. In your case, I think it is the CSS that was causing a problem. It was not loaded yet
stackoverflow.com/questions/45702723/
defer
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
elementAddMenu.innerHTML += '<div class="checkbox"></div>
elementAddMenu.innerHTML += '<div class="checkbox" onclick="setCheckBox()"></div>
var checkbox = document.getElementsByClassName('checkbox')[0];
checkbox.onclick = function() {
result = setCheckBox(checkbox);
};
.main {
border: 1px solid red;
width: 500px;
height: 600px;
position: relative;
}
.main a {
position: absolute;
right: 15px;
bottom: 15px;
}