简体   繁体   English

有没有办法强制javascript函数首先运行

[英]Is there a way to force a javascript function to run first

I have a javascript function on a page that dynamically changes the link for a nav item. 我在页面上有一个javascript函数,可以动态更改导航项的链接。 Is there any way to guarantee this runs first before any other javascript besides it being the first on the page? 有什么办法可以确保它首先在其他JavaScript之前首先运行?

I'm asking because this is an important item and there is a possibility that in the future that something else might break before this script making this unable to run. 我要问的是,这是一个重要的项目,并且将来在此脚本运行之前可能会发生其他故障,从而导致该脚本无法运行。

If the function is before in the code it will be executed before the rest as JS is a single threaded language. 如果函数在代码中位于之前,则它将在其余代码之前执行,因为JS是单线程语言。 Problem might come that the DOM manipulation is not ready before the rest of the functions try to get the DOM items. 问题可能出在其他功能试图获取DOM项之前,DOM操作尚未准备就绪。 That's the tricky part and hard to calculate and predict. 这是棘手的部分,很难计算和预测。

Easiest solution that comes to my mind is using a setTimeout checker with a flag or promises but it looks to me that maybe the approach to the problem should be rethink to not need setTimeouts at all. 我想到的最简单的解决方案是使用带有标志或承诺的setTimeout检查器,但在我看来,也许应该重新考虑解决问题的方法,根本不需要setTimeouts。 It's hard to be more precise with the actual code. 实际代码很难更加精确。

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

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