简体   繁体   English

如何在另一个函数中使用 document.onload?

[英]How to use document.onload in another function?

I have this function:我有这个功能:

function myfunc_embed() {
document.onload = function(){
   // myScript
  };
};

I call myfunc_embed() from a html page.我从 html 页面调用myfunc_embed() I want this to activate when the html page's DOM is loaded.我希望在加载 html 页面的 DOM 时激活它。 Looks like it doesn't work.看起来它不起作用。 However, if I put settimeout instead of document.onload() , it works fine.但是,如果我把 settimeout 而不是document.onload() ,它工作正常。 I am pretty new to JavaScript.我对 JavaScript 很陌生。 Is there something I am missing?有什么我想念的吗?

Note: It has to be called when DOM is loaded.注意:必须在加载 DOM 时调用它。

Edit: The code I am using to call myfunc_embed() is here -编辑:我用来调用myfunc_embed()的代码在这里 -

<script src="somewebsite.com/JS/some-func.js"></script> <script>;myfunc_embed();</script>

This script is written in a html page inside body element.该脚本是在 body 元素内的 html 页面中编写的。 There is no way I can change the position of the code.我无法更改代码的位置。 Full code: https://pastebin.com/f7GSFuNR完整代码: https : //pastebin.com/f7GSFuNR

You don't need to put it in the onload function, the script will work fine without using onload.你不需要把它放在 onload 函数中,脚本可以在不使用 onload 的情况下正常工作。 you just need to call your main function from the HTML你只需要从 HTML 调用你的 main 函数

  function myfunc_embed(id){
  id.addEventListener("load", function(event) {
     alert("something loaded.");
      });
   }

if you want to call a function on loading of a specific element you can simply call the function after declaring the element like this:如果您想在加载特定元素时调用函数,您可以在声明元素后简单地调用该函数,如下所示:

 <h3 id="yourid">something</h3>
 <script type="text/javascript">
    myfunc_embed('yourid');              
  </script>

You dont need to use the way you have used it try this你不需要用你用过的方式试试这个

<body onload="myFunction()">


function myFunction(){
   // myScript
  };

or you can use a javaScript plugin called Jquery which can do what you need to to like this或者你可以使用一个名为 Jquery 的 javaScript 插件,它可以做你需要做的事情

$(document).ready(()=>{
   // your script
});

in this implementation the code runs when after the whole page has loaded so you don't need to worry about where you put this code that's the beauty of Jquery在此实现中,代码在整个页面加载后运行,因此您无需担心将此代码放在哪里,这就是 Jquery 的美妙之处

If the onload is not getting called, it means you are registering it too late.如果没有调用 onload,则意味着您注册它为时已晚。 Check document.readyState .检查document.readyState

function myScript () {
    // ...
}
function myfunc_embed() {
    if (document.readyState === 'complete') {
        myScript();
    } else {
        document.onload = function () {
            myScript();
        }
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM