我的小书签包含对插入到 body
中的“启动器”脚本的调用。在运行时,它会以类似的方式插入更多脚本(jQuery,实际应用程序)和 CSS。
书签
javascript:(function(){
var l = document.createElement('script');
l.setAttribute('type','text/javascript');
l.setAttribute('src','launcher.js');
document.body.appendChild(l);
})();
Launcher.js
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src','my actual script');
document.body.appendChild(s);
// I repeat a block like this once per script/css.
问题是如果小书签被点击两次,所有的脚本都会被再次插入。我怎样才能防止这种行为?
最佳答案
您可以在 window
对象上设置一个名称奇怪的属性,因此它不太可能仅在第一次运行时引起 namespace 冲突。在后续运行中,如果属性存在,代码将不会执行:
javascript:(function(){
// Test for existence of your weird property
if (!window.hasOwnProperty('yourWeirdPropertyX774x9ZZYy4')) {
// Run all your existing code
var l = document.createElement('script');
l.setAttribute('type','text/javascript');
l.setAttribute('src','launcher.js');
document.body.appendChild(l);
// Set the flag so this won't run again
window.yourWeirdPropertyX774x9ZZYy4 = true;
}
})();
关于javascript - 如何强制小书签只运行一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7373993/