简体   繁体   中英

Organizing Javascript w/ jQuery

I am tinkering around with jQuery and am finding it very useful and almost exciting.

As of now, I am referencing the jQuery script via Google's CDN and I store plugins I use locally in a static/scripts directory.

Naturally, each page has its own individual implementation of components that are required for the features it currently offers. IE the main page has the Twitter plugin whereas the login page has form validation logic and password strength metering. However, certain components (navigation bar) for example use the same script across multiple pages.

Admittedly so, I am not a fan of putting javascript code in the header of a page, but I rather prefer to have it in an external file (for caching, re-usability, and optimization purposes).

My question is, what is the preferred route for organizing the external files. I wanted to try and keep it to one javascript file for the entire site to reduce IO requests. However, I am not sure how to implement document ready functions on a conditional per page bases.

$(document).ready(function () { ... }

Is there some way to reference a page by some method (preferably id based and not a url conditional).

Thank you in advance for your time!

You should try REQUIRE JS .

This will allow you to load only those plugins the pages where you need them, and unload them again if they are not needed anymore.

Then again, it might be overkill. It really depends on the size of your project.

Paul Irish:

http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/

This will allow you to block your scripts by body class/ID and execute them automatically.

First you might want to use YUI Compressor or some other JS compressing tool. Then perhaps creating a resource file (resx) for your JavaScript is the way to go. Then just reference the resource within your code. This is the approach Telerik took for their RadControl ASP.NET AJAX control framework.

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