开发者

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

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 bi开发者_JS百科g 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.


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:

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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜