We are using a small extension that auto-applies coupons from a link.
The extension had pop-up JS based on jQuery:
<script>
jQuery.noConflict();
jQuery(function() {
var appendthis = ("<div class='modal-overlay js-modal-close'></div>");
jQuery(document).ready(function(e) {
//e.preventDefault();
jQuery("body").append(appendthis);
jQuery(".modal-overlay").fadeTo(500, 0.7);
//$(".js-modalbox").fadeIn(500);
var modalBox = 'popup1';
jQuery('#' + modalBox).fadeIn(jQuery(this).data());
});
jQuery(".js-modal-close, .modal-overlay").click(function() {
jQuery(".modal-box, .modal-overlay").fadeOut(500, function() {
jQuery(".modal-overlay").remove();
});
});
jQuery(window).resize(function() {
jQuery(".modal-box").css({
top: (jQuery(window).height() - jQuery(".modal-box").outerHeight()) / 2,
left: (jQuery(window).width() - jQuery(".modal-box").outerWidth()) / 2
});
});
jQuery(window).resize();
});
</script>
It was our highest traffic page, in order to increase page speed we were removing unnecessary libraries and jQuery was one of them. So we needed to turn this code into pure JS.
The dev commented:
As far as I can see, this script performs a very simple task in a very complicated way.
First: there is no need to use fadeIn\fadeOut methods in this case. These methods freeze browser in loading moment. We need to use CSS transitions and just add opacity.
Second: there is no need to change top and left params during resize. We can use CSS and make the browser do it for us.
He did small changes to CSS of the extension, and final pure JS equivalent is:
<script>
window.onload = function() {
document.getElementById("popup-wrapper").className += " modal-overlay_visible";
}
function closeMethod() {
document.getElementById("popup-wrapper").className += " modal-overlay_hidden";
}
function DOMready() {
var closeElements = document.getElementsByClassName("js-modal-close");
Array.from(closeElements).forEach(function(element) {
element.addEventListener('click', closeMethod);
});
}
document.addEventListener("DOMContentLoaded", DOMready);
</script>
My response to the comments asking why both load and DOMContentLoaded are used:
Yes, there is a reason to use DOMContentLoaded.
Since until the DOM is built, we can not add events to the elements, they simply do not exist.
For a sample, if I tried to get in global scope document.getElementsByClassName("modal-overlay__close"); this instruction would return []
Also, we can not show the popup until all popup styles and popup picture are loaded.
That's why, I use window load event.