简体   繁体   中英

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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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