完全呈现页面后运行javascript

Ran*_*nan 17 javascript jquery

我正在尝试创建语法高亮显示脚本.我尝试在一万行代码上使用我的脚本,所有我看到的是加载时的空白页面.脚本完成任务后,一切都会显示出来.顺便说一下,我在jQuery的ready函数中调用了我的脚本.

$(myFunction);
Run Code Online (Sandbox Code Playgroud)

该脚本应在页面完全呈现后执行,即使脚本尚未完成,用户也可以实际浏览页面.javascript将在后台运行,因为它会逐一突出显示代码,同时不会干扰页面的重复性.提前致谢.

编辑:

为了使这更清楚,我想在所有"渲染"而不是"加载"之后执行代码.屏幕上已经可以看到所有内容,用户可以实际看到代码在突出显示时生效.谢谢.

Ada*_*kis 22

你的意思是在所有图像都已加载后?

我认为window.onload是你正在寻找的东西

window.onload = function() {
    //dom not only ready, but everything is loaded
};
Run Code Online (Sandbox Code Playgroud)

编辑

根据Chris的评论,这是jQuery的方式:

$(window).load(function() {
    //dom not only ready, but everything is loaded
});
Run Code Online (Sandbox Code Playgroud)

  • 好的,我正在寻找的术语是非阻塞javascript。javascript不应阻止浏览器的呈现和响应。上面的解决方案用于在页面加载后执行代码,但是仍然阻止页面的呈现。有任何想法吗?谢谢。 (2认同)
  • `$(window).load(function() { ... }` 已被弃用。您必须使用 `$(window).on('load', function(){ ...});`。[更多信息请点击这里](/sf/answers/2817689801/)。 (2认同)

syn*_*tik 5

window.onload 方法的问题

即使您使用该$(window).load方法,您的荧光笔内容也可能会在某些事情$(document).ready完成之前运行,因为可能到处都有很多异步回调函数。

我的方法

我使用了等待document.readyState == 'complete和的组合setTimeout。这个想法是我想等到页面完全呈现(因此是'complete'),然后进一步确保$(document).readyJQuery 包装器内容已经完成(因此是setTimeout)。

这是我将如何解决您的问题,假设 200 毫秒是$(document).ready(function(){ /*...*/ });完成内部所有内容的充足时间。

function highlighterAction() {
    // actually do the highlighting stuff here
}

function highlighter() {
    /*
      The short pause allows any required callback functions
      to execute before actually highlighting, and allows
      the JQuery $(document).ready wrapper to finish.
     */
    setTimeout(function() {
        highlighterAction();
    }, 200);
}

/*
  Only trigger the highlighter after document fully loaded.  This is
  necessary for cases where page load takes a significant length
  of time to fully load.
*/
if (document.readyState == 'complete') {
    highlighter();
} else {
    document.onreadystatechange = function () {
        if (document.readyState === "complete") {
            highlighter();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

如果您还没有尝试过,9 年后……

$(document).ready(function () {
    window.setTimeout('ctlEmployeeEdit.document_load()', 50);
    });
Run Code Online (Sandbox Code Playgroud)

我想如果您将时间设置为 9 毫秒,页面可能会呈现,但这只是我的假设!