Question

JavaScript not correctly running on initial load

  • 6 July 2023
  • 4 replies
  • 87 views

Hello,

We are currently experiencing challenges with JavaScript inputted into our Rich Text Editor(s) (RTE). Whilst inputting JavaScript into the editor and publishing it is not an issue, rendering on the front-end is.

The front-end will correctly run the JavaScript after refreshing the page, not on initial load.

We would greatly appreciate any assistance or insight into this problem.

Thank you,

Luke


4 replies

I would like to give this topic a quick boost in order to see if anyone is able to provide assistance.

Hi Luke,

 

My first thought is that when you receive and add that bit of Javascript, the page has already been rendered and the newly added Javascript is not getting evaluated. Which would also explain which it works the second time, as the browser would likely fetch it from cache.

You might want to try to force the evaluation of that code by running an eval.

 

If that does not work, please share your code so we can take a quick look at it :)

Hi Luke,

 

My first thought is that when you receive and add that bit of Javascript, the page has already been rendered and the newly added Javascript is not getting evaluated. Which would also explain which it works the second time, as the browser would likely fetch it from cache.

You might want to try to force the evaluation of that code by running an eval.

 

If that does not work, please share your code so we can take a quick look at it :)

Thank you for your response.

I have embedded the JavaScript code we are using below for review.

  <script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
function showTab(event, tabName) {
var tabContents = document.getElementsByClassName('tab-content');
for (var i = 0; i < tabContents.length; i++) {
tabContents[i].style.display = 'none';
}

var tabButtons = document.getElementsByClassName('tab-button');
for (var i = 0; i < tabButtons.length; i++) {
tabButtons[i].classList.remove('active');
}

document.getElementById(tabName).style.display = 'block';
event.currentTarget.classList.add('active');
}

// Attach event listeners to tab buttons
var tabButtons = document.getElementsByClassName('tab-button');
for (var i = 0; i < tabButtons.length; i++) {
tabButtons[i].addEventListener('click', function(event) {
var tabName = event.currentTarget.getAttribute('data-tab');
showTab(event, tabName);
});
}
});
</script>

Any additional pointers would be greatly appreciated.

Thank you,

Luke

Hi Luke,

 

Did the eval approach help?

Seems like the code you sent over is the script that is being added via Contentstack in the RTE field - is that correct?

I can only help further if I take a look at the code that adds that script to the page after receiving the JSON response from our API - this is the bit which might require an eval() call.

Reply