简体   繁体   English

尝试与window.onload一起执行两个JavaScript文件

[英]Trying to execute two JavaScript files together with window.onload

I've got two separate JavaScript files linked to one HTML document and when I run it, it seems the second JS file overrides the first. 我有两个单独的JavaScript文件链接到一个HTML文档,当我运行它时,似乎第二个JS文件会覆盖第一个JS文件。 I think it has to do with the window.onload being called in each file but am not sure how to work around that. 我认为这与在每个文件中调用window.onload有关,但不确定如何解决。

I've tried using window.onloadend on one of the JS files and window.onload on the other but with the same results, the window.onloadend is the only file that is executed. 我试过在一个JS文件上使用window.onloadend,在另一个JS文件上使用window.onload,但结果相同,window.onloadend是唯一执行的文件。

file1.js file1.js

function init() {
    applyFunction();
    prefillForm();
    var applyForm = document.getElementById("applyForm");
    applyForm.onsubmit = validate;
}

window.onload = init;

file2.js file2.js

function init() {
    currentPage();
    timer();
}

window.onload = init;

Whenever you assign to an on- property, you will overwrite whatever was previously attached to that property, and when the event fires, only the latest handler will run. 每当您分配给on-属性时,您都将覆盖先前附加到该属性的任何内容,并且在事件触发时,将仅运行最新的处理程序。 Use addEventListener instead: 使用addEventListener代替:

window.addEventListener('load', init);

(put that in place of the .onload line in both files) (在两个文件中代替.onload行)

Or, if you don't have to wait for the entire document to load (including things like images), you might listen for DOMContentLoaded instead, which will trigger more quickly. 或者,如果您不必等待整个文件加载(包括像图像),你可能会倾听DOMContentLoaded代替,这将引发更迅速。 The DOM and all elements will be populated, though not all resources may have been downloaded: DOM和所有元素将被填充,尽管并非所有资源都已下载:

window.addEventListener('DOMContentLoaded', init);

Or eventually you can rename Init functions to be not unique and in HTML call an anonymous function, which calls them both sequentially. 或者最终您可以将Init函数重命名为不唯一的,并在HTML中调用一个匿名函数,该函数将依次调用它们。 And in HTML call them: 并在HTML中调用它们:

load = () => {
   Init1();
   Init2();
}

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

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