Home > Software design >  Is it possible to have javascript update an input value on a page before the page loads?
Is it possible to have javascript update an input value on a page before the page loads?

Time:11-26

I have an <input id="my_field" type="number"> element on a page.

I have this code on my page:

$(document).ready(function() {
    $("#my_field").val(parseInt($("#my_field").val())   1);
});

This works, but looks unprofessional. When the page loads, the <input> field loads with the original value, and half a second later, updates to the new, incremented value.

Is there any way to make it increment the value before its initially drawn by the browser, so that the original value doesn't flash on the screen?

CodePudding user response:

You don't need to wait for $(document).ready - you only need to wait for the input to exist.

You can have the script run soon after the <input> in the HTML, eg:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="my_field" type="number" value="5">
<!-- make sure there isn't a whole lot of code/markup in between -->
<script>
$("#my_field").val(parseInt($("#my_field").val())   1);
</script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

You can also insert the script beforehand, and use a MutationObserver to wait for the <input> to exist, though this technique should only be needed for large pages when there's too much content, and the script and input can't be put close to each other.

<script>
new MutationObserver((_, observer) => {
  const my_field = document.querySelector('#my_field');
  if (!my_field) return;
  my_field.value = Number(my_field.value)   1;
  observer.disconnect();
})
  .observe(document.body, { childList: true, subtree: true });
</script>
<input id="my_field" type="number" value="5">
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

There's no need to require a big library like jQuery in order to do something so trivial - not having to load a big library will reduce load times in some cases.

  • Related