本文介绍了jQuery:强制执行document.ready()调用的执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用具有多个代码块的代码库来设置document.ready()(jQuery)上的某些行为.有没有一种方法可以强制在其他块之前调用一个特定块?

I'm working on a codebase with multiple blocks of code setting some behavior on document.ready() (jQuery). Is there a way to enforce that one specific block is called before any of the others?

背景:我需要在自动化测试环境中检测JS错误,因此需要在其他任何JS代码执行之前开始记录JS错误的代码.

Background:I need to detect JS errors in an automated testing environment, so I need the code that starts logging JS errors to execute before any other JS code executes.

推荐答案

document.ready()回调按注册顺序调用.如果您先注册测试回调,它将首先被调用.

document.ready() callbacks are called in the order they were registered. If you register your testing callback first, it will be called first.

此外,如果您的测试代码实际上不需要操纵DOM,那么您可以在解析代码时运行它,而不必等到DOM准备就绪后再调用其他document.ready()回调,然后再运行.或者,也许您可​​以立即运行部分测试代码,并将仅使用DOM的部分推迟到document.ready().

Also if your testing code does not actually need to manipulate the DOM, then you may be able to run it as the code is parsed and not wait until the DOM is ready which would run before the other document.ready() callbacks get called. Or, perhaps you could run part of your testing code immediately and defer only the part that uses the DOM until document.ready().

另一个想法是(仅出于测试目的)您可以使用经过稍微修改的jQuery版本运行,该版本在document.ready()上添加了一个标志,该标志在传递并设置为true时指示首先调用该函数,也可以添加一个新方法document.readyFirst(),它将首先调用您的函数.这将涉及对jQuery中document.ready()处理代码的细微更改.

Another idea is (for testing purposes only) you could run with a slightly modified version of jQuery that added a flag to document.ready() that when passed and set to true indicated to call that function first or you could add a new method document.readyFirst() that would call your function first. This would involve minor changes to the document.ready() processing code in jQuery.

这篇关于jQuery:强制执行document.ready()调用的执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 15:23