gpt4 book ai didi

javascript - addEventListener 加载在 Firefox 上触发两次

转载 作者:行者123 更新时间:2023-12-04 10:31:26 25 4
gpt4 key购买 nike

我使用这个简单的脚本加载器在加载主 CSS 后动态加载 Javascript。
像 Safari/Chrome 这样的浏览器可以完美运行,并且一次加载脚本。

但是 Firefox 会触发该事件两次,导致页面无法正常工作。

我怎样才能防止这种情况?

var Loader = function () {};

Loader.prototype = {
require: function (scripts, delay, id, callback) {
this.loadCount = 0;
this.totalRequired = scripts.length;
this.callback = callback;

var self = this;

this.timerID = window.setTimeout(function () {
for (var i = 0; i < scripts.length; i++) {
self.writeScript(scripts[i], id[i]);
}
window.clearTimeout(self.timerID);
}, delay);
},
loaded: function (evt) {
this.loadCount++;

if (this.loadCount === this.totalRequired && typeof this.callback == 'function') {
this.callback.call();
}
},
writeScript: function (src, id) {
var self = this;
var s = document.createElement('script');
s.defer = true;
s.id = id;
s.src = src;

s.addEventListener('load', function (e) {
self.loaded(e);
}, false);

document.body.appendChild(s);
}
};

function initJS(vendor, js) {
var vendor_loader = new Loader();
vendor_loader.require(vendor,
0,
['js1'],
function () {
var js_loader = new Loader();
js_loader.require(js, 500, ['js2', 'js3', 'js4']);
});
}
<head>
<link rel="stylesheet" href="/dist/styles/screen.css" media="print" onload="this.media='all';initJS(['/dist/scripts/vendor.js'],['/dist/scripts/main.js', '/dist/scripts/addons.js', '/dist/scripts/recaptcha.js']);">
</head>

最佳答案

设置 this.media导致 link标记重新加载,因此您会收到两次对 onload 的调用.

<head>
<link rel="stylesheet" href="https://cdn.sstatic.net/Shared/stacks.css?v=f6dc2e55f461" onload="this.media='all';console.log('hello')">
</head>


比较一下:

<head>
<link rel="stylesheet" href="https://cdn.sstatic.net/Shared/stacks.css?v=f6dc2e55f461" onload="console.log('hello')">
</head>


所以,我想,改变 media属性来自 printall并且不要在加载时设置媒体值。

关于javascript - addEventListener 加载在 Firefox 上触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60410013/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com