【发布时间】:2022-01-16 07:12:04
【问题描述】:
有效!
你不会相信那有多烦人。
这是工作代码,有人可以帮我优化代码吗?
有没有什么技巧可以缩短 js 或者让它更快? (网站也跑pagespeed,js已经优化了,还是有点慢)
JS:
window.onload = function checkCookie() {
if (document.cookie.split(';').some((item) => item.trim().startsWith('TechStatCookie='))) {
document.getElementById("CookiePopup").style.display = "none";
console.log("TechStatCookie detected ");
}
else {
console.log("TechStatCookie NOT detected ");
}
};
function _yesCookie() {
var now = new Date();
now.setTime(now.getTime() + 2419200000);
document.cookie = "YesCookie = set; expires=; path=/; SameSite=Strict; Secure" + now.toUTCString();
document.cookie = "TechStatCookie=1; expires=; path=/; SameSite=Strict; Secure" + now.toUTCString();
console.log("TechStatCookie set " + now.toUTCString());
document.cookie = 'NoCookie=; Max-Age=-99999999; path=/; SameSite=Strict; Secure';
window.ga = window.ga || function() {
(ga.q = ga.q || []).push(arguments)
};
ga.l = +new Date;
ga('create', 'UA-XXXXXXXX-X', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
var gascript = document.createElement("script");
gascript.async = true;
gascript.src = "https://www.google-analytics.com/analytics.js";
document.getElementsByTagName("head")[0].appendChild(gascript, document.getElementsByTagName("head")[0]);
console.log("Tracking enabled! " + now.toUTCString());
document.getElementById("CookiePopup").style.display = "none";
}
function _noCookie() {
var now = new Date();
now.setTime(now.getTime() + 604800000);
document.cookie = "NoCookie = set; expires=; path=/; SameSite=Strict; Secure" + now.toUTCString();
document.cookie = "TechStatCookie=1; expires=; path=/; SameSite=Strict; Secure" + now.toUTCString();
console.log("TechStatCookie set " + now.toUTCString());
document.cookie = 'YesCookie=; Max-Age=-99999999; path=/; SameSite=Strict; Secure';
console.log("Tracking disabled... " + now.toUTCString());
document.getElementById("CookiePopup").style.display = "none";
}
HTML:
<section id="CookiePopup">
<br>
<h1>Datenschutz</h1><br>
<embed src="https://example.com/update.html" width="100%" height="250px">
<p>blablabla</p>
<br>
<button class="ycookie" onclick='_yesCookie()' title="OK"><i class="far fa-check-circle"></i></button>
<button class="ncookie" onclick='_noCookie()' title="NEIN"><i class="far fa-times-circle"></i></button>
</section>
【问题讨论】:
-
因为您的
function声明嵌套在另一个范围(try块)中,它们不会被提升为全局级函数。 -
要修复它,只需删除
try语句(及其大括号和catch块) - 或前向声明try之外的函数并在@987654328 中定义它们@.
标签: javascript html optimization