页面加载完成后执行javascript(Execute javascript after page load is complete)

编程入门 行业动态 更新时间:2024-10-25 22:26:44
页面加载完成后执行javascript(Execute javascript after page load is complete)

我有一个预先呈现的内容和一些尚未呈现的内容的HTML页面。 我想立即显示预渲染的内容,然后开始渲染其余的内容。 我没有使用jQuery

请参阅以下片段。 我尝试了多种方法,包括在关闭body标记之前注入脚本,并提供脚本来填充DOM,作为window.onload , document.body.onload和document.addEventListener('DOMContentLoaded')的回调。 在任何情况下,在呈现其余内容之前,页面不会显示预先呈现的内容。

<html><head></head>
  <body>
    <header>What it is, my doge?</header>
    <div id="main"></div>
    <script>
      var main = document.getElementById('main');
      for (var i = 0; i < 500; i++)
        main.innerText += new Date();
    </script>
  </body>
</html> 
  
 

<html><head></head>
  <body>
    <header>What it is, my doge?</header>
    <div id="main"></div>
    <script>
      var main = document.getElementById('main');
      document.body.onload = function() {
        for (var i = 0; i < 500; i++)
          main.innerText += new Date();
      };
    </script>
  </body>
</html> 
  
 

<html><head></head>
      <body>
        <header>What it is, my doge?</header>
        <div id="main"></div>
        <script>
          var main = document.getElementById('main');
          window.onload = function() {
            for (var i = 0; i < 500; i++)
              main.innerText += new Date();
          };
        </script>
      </body>
    </html> 
  
 

<html><head></head>
      <body>
        <header>What it is, my doge?</header>
        <div id="main"></div>
        <script>
          var main = document.getElementById('main');
          document.addEventListener('DOMContentLoaded', function() {
            for (var i = 0; i < 500; i++)
              main.innerText += new Date();
          });
        </script>
      </body>
    </html> 
  
 

一个已经工作的案例是window.setTimeout和0超时。 然而,这只是推迟了这个功能,直到没有什么可做的事情。 这是最佳做法吗?

<html><head></head>
<body>
    <header>What it is, my doge?</header>
    <div id="main"></div>
    <script>
      var main = document.getElementById('main');
      window.setTimeout(function() {
        for (var i = 0; i < 500; i++)
          main.innerText += new Date();
      }, 0);
    </script>
</body>
</html> 
  
 

I have an html page with some pre-rendered content and some yet un-rendered content. I want to display the pre-rendered content immediately, and then begin rendering the rest of the content. I am not using jQuery.

See the following snippet. I have tried this various ways, including injecting my script before the closing body tag and providing my script to populate the DOM as a callback to window.onload, document.body.onload, and document.addEventListener('DOMContentLoaded'). In every case, the page does not display the pre-rendered content until the rest of the content is rendered.

<html><head></head>
  <body>
    <header>What it is, my doge?</header>
    <div id="main"></div>
    <script>
      var main = document.getElementById('main');
      for (var i = 0; i < 500; i++)
        main.innerText += new Date();
    </script>
  </body>
</html> 
  
 

<html><head></head>
  <body>
    <header>What it is, my doge?</header>
    <div id="main"></div>
    <script>
      var main = document.getElementById('main');
      document.body.onload = function() {
        for (var i = 0; i < 500; i++)
          main.innerText += new Date();
      };
    </script>
  </body>
</html> 
  
 

<html><head></head>
      <body>
        <header>What it is, my doge?</header>
        <div id="main"></div>
        <script>
          var main = document.getElementById('main');
          window.onload = function() {
            for (var i = 0; i < 500; i++)
              main.innerText += new Date();
          };
        </script>
      </body>
    </html> 
  
 

<html><head></head>
      <body>
        <header>What it is, my doge?</header>
        <div id="main"></div>
        <script>
          var main = document.getElementById('main');
          document.addEventListener('DOMContentLoaded', function() {
            for (var i = 0; i < 500; i++)
              main.innerText += new Date();
          });
        </script>
      </body>
    </html> 
  
 

One case that has worked is window.setTimeout with 0 timeout. However, this simply defers the function until there is nothing left to do. Is this the best practice, here?

<html><head></head>
<body>
    <header>What it is, my doge?</header>
    <div id="main"></div>
    <script>
      var main = document.getElementById('main');
      window.setTimeout(function() {
        for (var i = 0; i < 500; i++)
          main.innerText += new Date();
      }, 0);
    </script>
</body>
</html> 
  
 

最满意答案

最佳做法而言,没有一个。 就一个好的常见的可以接受的做法而言,有一些。 你已经击中了一个:

setTimeout(function() { }, 1);

在这种情况下,在所有其他联机处理结束后,该功能将在浏览器的最短超时期限内执行。

同样,如果你想确保你的函数在一些条件为真后马上运行,使用一个时间间隔:

var readyCheck = setInterval(function() { if (readyCondition) { /* do stuff */ clearInterval(readyCheck); } }, 1);

我在自己的工作中一直使用类似但更普遍的解决方案。 我在头文件中定义了一个辅助函数:

var upon = function(test, fn) { if (typeof(test) == 'function' && test()) { fn(); } else if (typeof(test) == 'string' && window[test]) { fn(); } else { setTimeout(function() { upon(test, fn); }, 50); } }; // upon()

...当依赖关系解决时我会触发其他功能:

upon(function() { return MyNS.Thingy; }, function() { // stuff that depends on MyNS.Thingy }); upon(function() { return document.readyState == 'complete';}, function() { // stuff that depends on a fully rendered document });

或者, 如果您想要更权威的良好做法 ,请按照Google的示例进行操作。 创建一个外部async脚本并在第一个script之前注入它:

var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = '/path/to/script.js'; var header_scripts = document.getElementsByTagName('script')[0]; header_scripts.parentNode.insertBefore(s, header_scripts);

Google的解决方案在理论上适用于所有浏览器(IE <10?),以尽可能快地执行外部脚本,而不会干扰文档加载。

如果你想要一个权威的通用实践 ,请查看jQuery的onready解决方案的源代码。

In terms of a best practice, there isn't one. In terms of a good, common, and acceptable practices, there are a handful. You've hit one:

setTimeout(function() { }, 1);

In this case, the function is executed within the browser's minimum timeout period after all other in-line processing ends.

Similarly, if you want to ensure your function runs shortly after some condition is true, use an interval:

var readyCheck = setInterval(function() { if (readyCondition) { /* do stuff */ clearInterval(readyCheck); } }, 1);

I've been using a similar, but more generalized solution in my own work. I define a helper function in the header:

var upon = function(test, fn) { if (typeof(test) == 'function' && test()) { fn(); } else if (typeof(test) == 'string' && window[test]) { fn(); } else { setTimeout(function() { upon(test, fn); }, 50); } }; // upon()

... and I trigger other functionality when dependencies are resolved:

upon(function() { return MyNS.Thingy; }, function() { // stuff that depends on MyNS.Thingy }); upon(function() { return document.readyState == 'complete';}, function() { // stuff that depends on a fully rendered document });

Or, if you want a more authoritative good practice, follow Google's example. Create an external async script and inject it before your first header script:

var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = '/path/to/script.js'; var header_scripts = document.getElementsByTagName('script')[0]; header_scripts.parentNode.insertBefore(s, header_scripts);

Google's solution theoretically works on all browsers (IE < 10?) to get an external script executing as soon as possible without interfering with document loading.

If you want an authoritative common practice, check the source for jQuery's onready solution.

更多推荐

本文发布于:2023-04-27 22:43:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329197.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加载   页面   完成后   javascript   complete

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!