我的bookmarklet包含对插入到正文中的“启动器”脚本的调用.在运行时,它以类似的方式插入更多脚本(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.
问题是如果单击两次书签,则会再次插入所有脚本.我该如何防止这种行为?
解决方法
您可以在窗口对象上设置一个奇怪命名的属性,因此在第一次运行时不太可能导致命名空间冲突.在后续运行中,如果属性存在,代码将不会执行:
- 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;
- }
- })();