我有2个外部JavaScript文件,它们都通过 window.onload 调用函数。文件冲突,因此只有第二个js文件正在工作。
如何修复 window.onload 以便这两个功能都有效?我应该在HTML文件中执行此操作还是可以在其中一个js文件中修复它?
HTML标题是:
<link type="text/css" rel="stylesheet" href="house.css" />
<style type="text/css"></style>
<script type="text/javascript" src="slideshow_library.js"></script>
<script type="text/javascript" src="slideshow.js"></script>
<script type="text/javascript" src="house.js"></script>
house.js:
var $ = function(id){
return document.getElementById(id);
}
var calculateClick = function() {
console.log("click, calculate click is running");
//blahblahblah, lots of code
}
window.onload = function(rental){
console.log("onload, javascript is running");
console.log(rental);
$("calculate").onclick = calculateClick;
}
第二个window.onload是2个js文件:
slideshow.js:
var slideShow;
window.onload = function (slideShow) {
var params = {
//blahblahblah lots of code
}
}
slideshow_library.js:
var $ = function(id) {
return document.getElementById(id);
}
var SlideShow = function( params ){
//blahblah blah even more code
}
SlideShow.prototype.displayImage = function(){
//blahblah blah even more code
}
SlideShow.prototype.displayNextImage = function(){
//blahblah blah even more code
}
SlideShow.prototype.displayPreviousImage = function(){
//blahblah blah even more code
}
SlideShow.prototype.togglePlay = function(){
//blahblah blah even more code
}
答案 0 :(得分:7)
请勿使用旧的window.onload
事件模型。这不是很灵活 - 正如您所注意到的那样 - 并且不再需要浏览器支持。
jQuery使这很简单;在每个JS文件中将window.onload = function
更改为$(function)
。
纯JS解决方案:将其更改为window.addEventListener('load', function)
。
答案 1 :(得分:0)
如果你被允许/熟悉使用JQuery,那就可以这样做:
$(window).on('load', function() {
//<-- do the rest here..
});
如果您仍在寻找纯粹的js,请尝试使用此示例,而不是window.onload
,而是使用document.readyState
:
first.js
(function(window, document) {
var t = setInterval(function() {
if('complete' === document.readyState) {
clearInterval(t);
alert('first js loaded ...');
}
}, 10);
})(window, document);
last.js
(function(window, document) {
var t = setInterval(function() {
if('complete' === document.readyState) {
clearInterval(t);
alert('last js loaded ...');
}
}, 10);
})(window, document);