如何强制小书签只运行一次?
我的小书签包含对插入到 body
中的“启动器”脚本的调用。当它运行时,它会以类似的方式插入更多脚本(jQuery,实际应用程序)和 CSS。
Bookmarklet
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.
问题是,如果单击该书签两次,所有脚本都将再次插入。我怎样才能防止这种行为?
My bookmarklet consist of a call to a 'launcher' script that is inserted into body
. As it runs, it inserts in a similar way more scripts (jQuery, the actual application), and a CSS.
Bookmarklet
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.
The problem is that if the bookmarklet is clicked twice, all the scripts will be inserted again. How can I prevent this behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在
window
对象上设置一个属性,该属性的名称很奇怪,因此仅在第一次运行时不太可能导致命名空间冲突。在后续运行中,如果该属性存在,则代码将不会执行:You can set a property on the
window
object which is oddly named, so it is unlikely to cause namespace collisions, on the first run only. On subsequent runs, the code will not execute if the property is present:我发现执行此操作的最简洁方法是命名加载外部 js 文件的函数,该函数与我希望每次用户单击小书签时运行的外部文件内的函数同名。这样,当第一次单击小书签时,它会加载外部文件,并在随后单击时运行外部文件中的函数。
这是一些 sudo 代码:
这将是 bookmarklet 链接的 url 中的代码
external.js 文件将包含一个具有相同名称的函数,如下所示:
这样,当加载外部文件时您的函数(示例函数是 bookmarklet.js) click)现在在外部加载的文件中运行该函数,并且不会再次加载外部js文件。
I found the cleanest way for me to do this was to name the function that loads the external js file, the same name as a function inside the external file that I want to be ran everytime the user clicks the bookmarklet. This way when the bookmarklet is clicked the first time, it loads the external file and on subsquent clicks a function in the external file is ran.
Here is some sudo code:
This would be the code in the url of the bookmarklet link
The external.js file would contain a function with the same name like this:
This way when the external file is loaded your function (example function is bookmarklet.click) now runs the function inside the externally loaded file and will not load the external js file a second time.
在 JavaScript 中实现单例的最简单/最干净的方法?
一个示例关于在 JS 中实现单例的好方法。我不会复制/粘贴他的答案,但请仔细阅读:)
Simplest/Cleanest way to implement singleton in JavaScript?
An example on a good way to implement Singletons in JS. I won't copy/paste his answer, but give it a good read :)