Why does dynamically adding a viewport meta tag result in unwanted zoom?

During a legacy site update, inserting a viewport meta tag via JavaScript produces an unexpected zoom effect. The example below replicates the issue:

function insertViewportMeta() {
  const tag = document.createElement('meta');
  tag.setAttribute('name', 'viewport');
  tag.setAttribute('content', 'initial-scale=1');
  document.head.appendChild(tag);
}
insertViewportMeta();

How can this zoom behavior be prevented?

In my experience, dynamically inserting the viewport meta tag after the initial page load can lead to unexpected behavior because browsers may perform layout calculations based on settings that were active at page initialization. The browser might then attempt to adjust its rendering context when it detects the new viewport declaration, resulting in a zoom or scaling glitch. An approach that has worked for me is ensuring the meta tag is present as early as possible in the HTML, ideally by embedding it statically. When dynamic insertion is required, executing the script before the page loads completely also helps prevent these issues.