如何在页面加载时运行函数?

发布于 2024-10-14 17:11:17 字数 449 浏览 5 评论 0原文

我想在页面加载时运行一个函数,但我不想在 标记中使用它。

我有一个脚本,如果我在 中初始化它,就会运行它,如下所示:

function codeAddress() {
  // code
}
<body onLoad="codeAddress()">

但我想在没有 的情况下运行它 我已经尝试了很多东西,例如:

window.onload = codeAddress;

但它不起作用。

那么当页面加载时如何运行它呢?

I want to run a function when the page is loaded, but I don’t want to use it in the <body> tag.

I have a script that runs if I initialise it in the <body>, like this:

function codeAddress() {
  // code
}
<body onLoad="codeAddress()">

But I want to run it without the <body onload="codeAddress()"> and I have tried a lot of things, e.g. this:

window.onload = codeAddress;

But it is not working.

So how do I run it when the page is loaded?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

爱人如己 2024-10-21 17:11:17

window.onload = codeAddress; 应该可以工作 - 这里有一个演示,以及完整的代码:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('ok');
        }
        window.onload = codeAddress;
        </script>
    </head>
    <body>
    
    </body>
</html>


<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('ok');
        }
        
        </script>
    </head>
    <body onload="codeAddress();">
    
    </body>
</html>

window.onload = codeAddress; should work - here's a demo, and the full code:

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('ok');
        }
        window.onload = codeAddress;
        </script>
    </head>
    <body>
    
    </body>
</html>


<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript">
        function codeAddress() {
            alert('ok');
        }
        
        </script>
    </head>
    <body onload="codeAddress();">
    
    </body>
</html>

扛起拖把扫天下 2024-10-21 17:11:17

自 jQuery 发布以来,原生 JavaScript 不再使用 jQuery 或 window.onload,而是采用了一些很棒的功能。所有现代浏览器现在都有自己的 DOM 就绪功能,无需使用 jQuery 库。

如果你使用原生 Javascript,我会推荐这个。

document.addEventListener('DOMContentLoaded', function() {
    alert("Ready!");
}, false);

Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.

I'd recommend this if you use native Javascript.

document.addEventListener('DOMContentLoaded', function() {
    alert("Ready!");
}, false);
甜味拾荒者 2024-10-21 17:11:17

替代解决方案。我更喜欢这种方式,因为它简洁且代码简单。

(function () {
    alert("I am here");
})();

这是一个匿名函数,未指定名称。
这里发生的是,函数是一起定义和执行的。
将其添加到正文的开头或结尾,具体取决于它是在加载页面之前还是在加载所有 HTML 元素之后立即执行。

Alternate solution. I prefer this for the brevity and code simplicity.

(function () {
    alert("I am here");
})();

This is an anonymous function, where the name is not specified.
What happens here is that, the function is defined and executed together.
Add this to the beginning or end of the body, depending on if it is to be executed before loading the page or soon after all the HTML elements are loaded.

我们只是彼此的过ke 2024-10-21 17:11:17

采用 Darin 的答案,但采用 jQuery 风格。 (我知道用户要求使用 javascript)。

运行小提琴

$(document).ready ( function(){
   alert('ok');
});​

Taking Darin's answer but jQuery style. (I know the user asked for javascript).

running fiddle

$(document).ready ( function(){
   alert('ok');
});​
隔纱相望 2024-10-21 17:11:17

window.onload = function() { ...等等不是一个很好的答案。

这可能会起作用,但它也会破坏已经挂钩该事件的任何其他函数。或者,如果另一个函数在您的事件之后挂钩到该事件,它将破坏您的事件。
因此,您可能会在事后花费大量时间试图找出为什么以前有效的东西不再有效。

更可靠的答案此处:

if(window.attachEvent) {
    window.attachEvent('onload', yourFunctionName);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            yourFunctionName(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = yourFunctionName;
    }
}

我一直在使用的一些代码,我忘记了在哪里找到它以给予作者荣誉。

function my_function() {
    // whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}

希望这有帮助:)

window.onload = function() { ... etc. is not a great answer.

This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours.
So, you can spend lots of hours later trying to figure out why something that was working isn't anymore.

A more robust answer here:

if(window.attachEvent) {
    window.attachEvent('onload', yourFunctionName);
} else {
    if(window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            yourFunctionName(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = yourFunctionName;
    }
}

Some code I have been using, I forget where I found it to give the author credit.

function my_function() {
    // whatever code I want to run after page load
}
if (window.attachEvent) {window.attachEvent('onload', my_function);}
else if (window.addEventListener) {window.addEventListener('load', my_function, false);}
else {document.addEventListener('load', my_function, false);}

Hope this helps :)

新一帅帅 2024-10-21 17:11:17

尝试 readystatechange

document.addEventListener('readystatechange', () => {    
  if (document.readyState == 'complete') codeAddress();
});

,其中状态为:

  • 正在加载 - 文档正在加载(没有触发snippet)
  • interactive - 文档被解析,在 DOMContentLoaded 之前触发
  • complete - 文档和资源被加载,在 window.onload 之前触发
<script>
  document.addEventListener("DOMContentLoaded", () => {
    mydiv.innerHTML += `DOMContentLoaded (timestamp: ${Date.now()})</br>`;
  });
  
  window.onload = () => {
    mydiv.innerHTML += `window.onload (timestamp: ${Date.now()}) </br>` ;
  } ;

  document.addEventListener('readystatechange', () => {
    mydiv.innerHTML += `ReadyState: ${document.readyState}  (timestamp: ${Date.now()})</br>`;
    
    if (document.readyState == 'complete') codeAddress();
  });

  function codeAddress() {
    mydiv.style.color = 'red';
  }
</script>

<div id='mydiv'></div>

Try readystatechange

document.addEventListener('readystatechange', () => {    
  if (document.readyState == 'complete') codeAddress();
});

where states are:

  • loading - the document is loading (no fired in snippet)
  • interactive - the document is parsed, fired before DOMContentLoaded
  • complete - the document and resources are loaded, fired before window.onload

<script>
  document.addEventListener("DOMContentLoaded", () => {
    mydiv.innerHTML += `DOMContentLoaded (timestamp: ${Date.now()})</br>`;
  });
  
  window.onload = () => {
    mydiv.innerHTML += `window.onload (timestamp: ${Date.now()}) </br>` ;
  } ;

  document.addEventListener('readystatechange', () => {
    mydiv.innerHTML += `ReadyState: ${document.readyState}  (timestamp: ${Date.now()})</br>`;
    
    if (document.readyState == 'complete') codeAddress();
  });

  function codeAddress() {
    mydiv.style.color = 'red';
  }
</script>

<div id='mydiv'></div>

困倦 2024-10-21 17:11:17

看一下 domReady 脚本,它允许设置多个函数在 DOM 加载时执行。它基本上是 Dom Ready 在许多流行的 JavaScript 库中所做的事情,但它是轻量级的,可以在外部脚本文件的开头进行获取和添加。

用法示例

// add reference to domReady script or place 
// contents of script before here

function codeAddress() {

}

domReady(codeAddress);

Take a look at the domReady script that allows setting up of multiple functions to execute when the DOM has loaded. It's basically what the Dom ready does in many popular JavaScript libraries, but is lightweight and can be taken and added at the start of your external script file.

Example usage

// add reference to domReady script or place 
// contents of script before here

function codeAddress() {

}

domReady(codeAddress);
吹泡泡o 2024-10-21 17:11:17

window.onload 将像这样工作:

function codeAddress() {
	document.getElementById("test").innerHTML=Date();
}
window.onload = codeAddress;
<!DOCTYPE html>
<html>
<head>
	<title>learning java script</title>
	<script src="custom.js"></script>
</head>
<body>
	<p id="test"></p>
	<li>abcd</li>
</body>
</html>

window.onload will work like this:

function codeAddress() {
	document.getElementById("test").innerHTML=Date();
}
window.onload = codeAddress;
<!DOCTYPE html>
<html>
<head>
	<title>learning java script</title>
	<script src="custom.js"></script>
</head>
<body>
	<p id="test"></p>
	<li>abcd</li>
</body>
</html>

可是我不能没有你 2024-10-21 17:11:17

一旦页面加载,该函数就会运行:

(*your function goes here*)(); 

或者:

document.onload = functionName();
window.onload = functionName(); 

As soon as the page load the function will be ran:

(*your function goes here*)(); 

Alternatively:

document.onload = functionName();
window.onload = functionName(); 
无力看清 2024-10-21 17:11:17
<script>
window.addEventListener('load', function () {    
    console.log('page loaded');
});
</script>
<script>
window.addEventListener('load', function () {    
    console.log('page loaded');
});
</script>
生生不灭 2024-10-21 17:11:17

我相信这是维持不同版本浏览器支持的最佳方式

if (window.addEventListener) {
   window.addEventListener("load", myFunction, false);
}
else if (window.attachEvent) {
   window.attachEvent("onload", myFunction);
}
else {
   window.onload = myFunction; //will override previously attached event listeners.
}

I believe this is the best way to maintain support across different versions of browsers

if (window.addEventListener) {
   window.addEventListener("load", myFunction, false);
}
else if (window.attachEvent) {
   window.attachEvent("onload", myFunction);
}
else {
   window.onload = myFunction; //will override previously attached event listeners.
}
赠佳期 2024-10-21 17:11:17

通用跨浏览器网页加载器

我编写了一个 JavaScript 页面加载器,它应该可以解决您在页面加载后加载函数的问题。与其他帖子不同,此网页加载器99.9% 跨浏览器兼容,并且可以在许多版本的浏览器(新旧)中运行。支持几乎所有浏览器中加载页面,包括 Internet Explorer 3-11、所有 Firefox 和 Chrome 浏览器、早期 Opera、所有移动浏览器、Netscape 4 和 6 系列等。

它将选择最快的页面加载事件或状态检查给定的浏览器并返回一个文本字符串,指示 JavaScript 可以安全地处理文档对象模型 (DOM)。应该可以在许多旧版浏览器中工作,但需要测试。将您的 JavaScript 函数或或库调用放在下面的“Start()”方法中,这样一旦脚本显示网页或 DOM 在浏览器中加载,它们就会被触发。

作为旁注,我建议您将此代码放置在以下位置:

  1. 在 html 页面的头部嵌入
  2. 在加载的外部

如果使用这些方法,脚本不应过多阻塞渲染。您希望此脚本在首次构建网页 DOM 时准备好,而不是之后,特别是因为页面的后续状态可能会延迟等待图像、视频和 JavaScript API 下载。

    // ======== AFTER PAGE LOADS CALL YOUR SCRIPTS HERE =========

    function Start(status) {

        // In most modern browsers the console should return:
        // "Browser Loader : Document : DOMContentLoaded : interactive"
        console.log(status);

        // add your script calls here...

    };



    // ======== JAVASCRIPT PAGE LOADER =========
    // Stokely Web Page loader, 2022

    if (document.readyState) {

        if (document.readyState === "complete" || document.readyState === "loaded") {

            Start("Browser Loader : Document : readyState : complete");

        } else {

            if (window.addEventListener) {

                // Never try and call 'DOMContentLoaded' unless the web page is still in an early loading state.

                if (document.readyState === 'loading' || document.readyState === 'uninitialized') {

                    window.addEventListener('DOMContentLoaded', function () {

                        // Most modern browsers will have the DOM ready after this state.

                        if (document.readyState === "interactive") {

                            Start("Browser Loader : Document : DOMContentLoaded : interactive");

                        } else if (document.readyState === "complete" || document.readyState === "loaded") {

                            Start("Browser Loader : Document : DOMContentLoaded : complete");

                        } else {

                            Start("Browser Loader : Document : DOMContentLoaded : load");

                        }

                    }, false);

                } else {

                    // FALLBACK LOADER : If the readyState is late or unknown, go ahead and try and wait for a full page load event. Note: This function below was required for Internet Explorer 9-10 to work because of non-support of some readyState values! IE 4-9 only supports a "readyState" of "complete".

                    if (document.readyState === 'complete' || document.readyState === "loaded") {

                        Start("Browser Loader : Document : readyState : complete");

                    } else {

                        window.addEventListener('load', function () {

                            Start('Browser Loader : Window : Event : load');

                        }, false);

                    }
                }

            // If 'addEventListener' is not be supported in the browser, try the 'onreadystate' event. Some browsers like IE have poor support for 'addEventListener'.

            } else {

                // Note: document.onreadystatechange may have limited support in some browsers.

                if (document.onreadystatechange) {

                    document.onreadystatechange = function () {

                        if (document.readyState === "complete" || document.readyState === "loaded"){

                            Start("Browser Loader : Document : onreadystatechange : complete");

                        } 

                        // OPTIONAL: Because several versions of Internet Explorer do not support "interactive" or get flagged poorly, avoid this call when possible.

                        //else if (document.readyState === "interactive") {
                            //Start("Browser Loader : Document : onreadystatechange : interactive");
                        //}

                    }

                } else {

                    // Note: Some browsers like IE 3-8 may need this more traditional version of the loading script if they fail to support "addeventlistener" or "onreadystate". "window.load" is a very old and very reliable page loader you should always fall back on.

                    window.onload = function() {

                            Start("Browser Loader : Window : window.onload (2)");

                    };

                }
            }
        }
    } else {

        // LEGACY FALLBACK LOADER. If 'document.readyState' is not supported, use 'window.load'. It has wide support in very old browsers as well as all modern ones. Browsers Firefox 1-3.5, early Mozilla, Opera < 10.1, old Safari, and some IE browsers do not fully support 'readyState' or its values. "window.load" is a very old and very reliable page loader you should always fall back on.

        window.onload = function () {

                Start("Browser Loader : Window : window.onload (1)");

        };

    };

注意:当您在 Web 浏览器中运行此脚本时,请务必按 F12 打开浏览器工具屏幕并检查控制台选项卡以查看结果。它会告诉您网页加载器在哪个阶段被触发以及何时调用“Start()”脚本。

在大多数现代浏览器(HTML5 或 2010 年后)中,应该在 HTML 标记的 DOM 或文档对象模型呈现后立即触发,但其余网页资源、CSS、图像、视频和其他文件仍在加载。在现代浏览器中,这通常处于“交互”和“完成”的就绪状态之间,并且 DOM 已构建,但浏览器仍在下载其他资源文件。这允许您的 JavaScript 很早就访问并开始操作 HTML 树或 DOM。

较旧的浏览器(例如 Internet Explorer v. 3-8 或 Netscape)不了解高级 DOM 检查,因此在调用 JavaScript 之前需要完全或“完全”加载 DOM 和所有页面资源。

Universal Cross-Browser Web Page Loader

I wrote a JavaScript page loader that should solve your issues loading a function after the page is loaded. This web page loader is 99.9% cross-browser compatible and works in many versions of browsers, old and new, unlike the other posts. Includes support for loading pages in nearly all browsers, including Internet Explorer 3-11, all Firefox and Chrome browsers, early Opera, all mobile browsers, Netscape 4 and 6 series, etc.

It will pick the fastest page load event or state check for a given browser and return a text string indicating JavaScript may safely process the Document Object Model (DOM). Should work in many legacy browsers, but test. Place your JavaScript functions or or library calls inside the "Start()" method below, so they are triggered as soon as the script says the web page or DOM is loaded in the browser.

As a side note, I recommend you place this code either:

  1. In the head of your html page in a embedded <script> block as a synchronous script, which pauses the page to load early.
    ...or...
  2. In a loaded external <script> tag file with the "async" attribute added so it loads quietly in parallel to your page but pauses html loading when download complete so it gets parsed and processed first.

The script should not render-block much if using these methods. You want this script ready when the web page DOM is first built and not after, especially since later states of the page could get delayed waiting for images, videos, and JavaScript API's to download.

    // ======== AFTER PAGE LOADS CALL YOUR SCRIPTS HERE =========

    function Start(status) {

        // In most modern browsers the console should return:
        // "Browser Loader : Document : DOMContentLoaded : interactive"
        console.log(status);

        // add your script calls here...

    };



    // ======== JAVASCRIPT PAGE LOADER =========
    // Stokely Web Page loader, 2022

    if (document.readyState) {

        if (document.readyState === "complete" || document.readyState === "loaded") {

            Start("Browser Loader : Document : readyState : complete");

        } else {

            if (window.addEventListener) {

                // Never try and call 'DOMContentLoaded' unless the web page is still in an early loading state.

                if (document.readyState === 'loading' || document.readyState === 'uninitialized') {

                    window.addEventListener('DOMContentLoaded', function () {

                        // Most modern browsers will have the DOM ready after this state.

                        if (document.readyState === "interactive") {

                            Start("Browser Loader : Document : DOMContentLoaded : interactive");

                        } else if (document.readyState === "complete" || document.readyState === "loaded") {

                            Start("Browser Loader : Document : DOMContentLoaded : complete");

                        } else {

                            Start("Browser Loader : Document : DOMContentLoaded : load");

                        }

                    }, false);

                } else {

                    // FALLBACK LOADER : If the readyState is late or unknown, go ahead and try and wait for a full page load event. Note: This function below was required for Internet Explorer 9-10 to work because of non-support of some readyState values! IE 4-9 only supports a "readyState" of "complete".

                    if (document.readyState === 'complete' || document.readyState === "loaded") {

                        Start("Browser Loader : Document : readyState : complete");

                    } else {

                        window.addEventListener('load', function () {

                            Start('Browser Loader : Window : Event : load');

                        }, false);

                    }
                }

            // If 'addEventListener' is not be supported in the browser, try the 'onreadystate' event. Some browsers like IE have poor support for 'addEventListener'.

            } else {

                // Note: document.onreadystatechange may have limited support in some browsers.

                if (document.onreadystatechange) {

                    document.onreadystatechange = function () {

                        if (document.readyState === "complete" || document.readyState === "loaded"){

                            Start("Browser Loader : Document : onreadystatechange : complete");

                        } 

                        // OPTIONAL: Because several versions of Internet Explorer do not support "interactive" or get flagged poorly, avoid this call when possible.

                        //else if (document.readyState === "interactive") {
                            //Start("Browser Loader : Document : onreadystatechange : interactive");
                        //}

                    }

                } else {

                    // Note: Some browsers like IE 3-8 may need this more traditional version of the loading script if they fail to support "addeventlistener" or "onreadystate". "window.load" is a very old and very reliable page loader you should always fall back on.

                    window.onload = function() {

                            Start("Browser Loader : Window : window.onload (2)");

                    };

                }
            }
        }
    } else {

        // LEGACY FALLBACK LOADER. If 'document.readyState' is not supported, use 'window.load'. It has wide support in very old browsers as well as all modern ones. Browsers Firefox 1-3.5, early Mozilla, Opera < 10.1, old Safari, and some IE browsers do not fully support 'readyState' or its values. "window.load" is a very old and very reliable page loader you should always fall back on.

        window.onload = function () {

                Start("Browser Loader : Window : window.onload (1)");

        };

    };

Note: When you run this script in a web browser, be sure to press F12 to pull up the browser tools screen and check the console tab to see the result. It will tell you at what stage the web page loader was triggered and when it called the 'Start()' script.

In most modern browsers (HTML5 or post-2010) it should be triggered as soon as the DOM or Document Object Model of HTML markup is rendered but the rest of the web page resources, CSS, images, video, and other files are still loading. In modern browsers this is usually between a readystate of "interactive" and "complete" and the DOM is built but the browser is still downloading other resource files. This allows your JavaScript to access and start manipulating the HTML tree or DOM very very early.

Older browsers like Internet Explorer v. 3-8 or Netscape, do not understand the advanced DOM checks so would require the full or "complete" load of the DOM and all page resources before calling your JavaScript.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文