I have the following DOM element change function using vanilla javascript where I change the span element that contains some text string of the DOM with page load event.
With the following code the DOM elements are changed as expected, but still see a minimal fraction of flickering before the DOM element change for the variable desktop
and mobile
.
Example of the flickering scenario:
- I see the tag span "Text I want to change" for a fraction of second.
- I see the changed tag span "text1 changed" after the content has fully loaded.
I think this is happening because the DOM changes are applied when the DOM content of the page is fully loaded. What I would like to do is to hide the existing tag elements until the changes have been applied, and then display it.
The elements structure for desktop
and mobile
I want to manipulate is like the following:
<span class="first-headline">Text I want to change</span>
See the concept below:
var changesObj = {
"us": {
title: "text1 changed"
},
"eu": {
title: "text2 changed"
}
};
function changes() {
var webshop = changesObj[window.location.pathname.split('/')[1]];
console.log(webshop);
var changesText;
if (!webshop) {
console.log('webshop not found');
}
changesText = webshop.title;
console.log(promobarText);
if (document.querySelector('.header-voucher-bar--desktop > div > a > span > span').innerText.length > 0) {
var desktop = document.querySelector('.header-voucher-bar--desktop > div > a > span > span');
console.log(desktop);
desktop.innerText = changesText;
console.log(desktop.innerText);
console.log("applied changes for dekstop");
}
if (document.querySelector('.header-voucher-bar--mobile > div > a > span > span').innerText.lenght > 0) {
var mobile = document.querySelector('.header-voucher-bar--mobile > div > a > span > span');
mobile.innerText = changesText;
console.log(mobile.innerText);
console.log("applied changes for mobile");
}
}
function invokeChanges() {
document.addEventListener("DOMContentLoaded", function() {
changes();
});
}
invokeChanges();
Is there a way maybe to initially hide the DOM element until the change to the existing element has been applied and then show it?
I was thinking of using something inline css rules like the following:
Set .style.visbility='hidden'
and when the text content is changed to show it with .style.visbility='visble'
.
But I'm not sure how this solution should be properly implemented in my code.
from Avoid flickering when changing existing DOM elements on page load event
No comments:
Post a Comment