acidzombie24 acidzombie24 - 2 months ago 7
HTML Question

Change html before rendering to avoid a flicker

I have code I'd like to run before the page is rendered. For example updating dates from absolute time to relative time or converting raw text (or markdown) to html. If I reload the page several times I can see occasionally there's flickering updating the changes. How do I run the code as it's drawn instead at the end where it needs to redraw everything?

I tried

document.addEventListener('beforeload'
it appears that event is depreciated and no longer supported in chrome

Answer

You'll need to think about your page lifecycle.

When your page is being loaded, if a <script> tag is encountered, it will immediately be executed, and prevent any more content being rendered until that script is complete. This isn't recommended practice.

But, to answer your question, you could do something like this:

<p>Your next reward will be available in <span id="nextRewardTime">3600</span>.</p>
<script type="text/javascript">
    var $el = $('#nextRewardTime');
    $el.text(format($el.text());
</script>

<p>Come back soon!</p>

Now, immediately after the first <p> is downloaded by the browser, it'll hit the <script> tag and execute the JS. Only once that is complete will it download the next <p> tag ('Come back soon!').

You can't attach an event handler to the Javascript before it's been rendered on the DOM, because... well... it's not on the DOM.

The better way of doing this is to format the thing correctly on the server in the first place.

Edit: Also, scattering script tags throughout your page makes your code really unmaintainable!

Comments