简体   繁体   English

我应该在哪里将只需要一页的JavaScript例程放在哪里?

[英]Where should I put a JavaScript routine needed only on one page?

I have the following prototype JavaScript code 我有以下原型JavaScript代码

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. 或者,我可以将其添加到为整个站点加载的一个大文件中,但是我尝试这样做,但是由于所有页面上都不存在元素“ agreement”,因此出现了错误。

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: 如果确实要将其移动到所有站点页面上都引用的文件中,为什么不添加添加click事件处理程序之前仅测试#agreement元素是否存在:

Event.observe( window, 'load', function() {
    if($('#agreement') != null){
        Event.observe( 'agreement', 'click', function() { alert("It works") });
    }
});

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. 话虽这么说,如果只在您网站的那个页面上使用它,我会将其保留为内联javascript,因为它是浏览器对资源的更少要求。

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. 但是 (总是有一个but)上述内容可能导致难以维护的项目,因为最终您可能会在标记中撒满很多内联JavaScript。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM