我应该将仅在一页上需要的 JavaScript 例程放在哪里?
我有以下原型 JavaScript 代码
Event.observe( window, 'load', function() {
Event.observe( 'agreement', 'click', function() { alert("It works") });
});
,它仅在我网站的一个页面上使用,组织它的最佳方式是什么?
我想我可以将它放在自己的文件中,并仅将其包含在该页面上。或者我可以将其添加到为整个站点加载的一个大文件中,但我尝试这样做,并收到错误,因为元素“协议”并不存在于所有页面上。
I have the following prototype JavaScript code
Event.observe( window, 'load', function() {
Event.observe( 'agreement', 'click', function() { alert("It works") });
});
It is used on only one page of my site, what is the best way to organise it?
I suppose I could put it in its own file, and include it only on that page. Or I could add it to one big file which is loaded for the whole site, but I tried doing that, and got an error because the element "agreement" does not exist on all pages.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您确实将其移动到所有网站页面上引用的自己的文件中,为什么不在添加单击事件处理程序之前测试 #agreement 元素是否存在:
也就是说,如果它只用于该事件在您网站的一个页面上,我会将其保留为内联 JavaScript,因为这样浏览器对资源的请求就少了。
但是(总有一个但是)上述情况可能会导致项目难以维护,因为您最终可能会在标记中散布大量内联 JavaScript。
If you do move it into its own file that is referenced on all site pages, why not just test for the existence of the #agreement element before adding the click event handler:
That being said, if it's only ever going to be used on that one page of your site, I would leave it as inline javascript as it's one less request the browser has to make for a resource.
But (there's always a but) the above can lead to projects that are difficult to maintain since you can end up with a lot of inline javascript sprinkled through your markup.