acidzombie24 acidzombie24 - 1 year ago 72
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

it appears that event is depreciated and no longer supported in chrome

Answer Source

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');

<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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download