Question: What I'm trying to achieve is that if i have 2 components nodes :

* component1 

	+ clientlib
		- component1.js
* component2 

	+ clientlib
		- component2.js

and i drag them into page1, then when page1 is generated, only component1.js and component2.js will be loaded when navigating to page1 . 

One approach i saw is to use custom `Tag Library` as described here : <http://www.icidigital.com/blog/best-approaches-clientlibs-aem-part-3/>

I have two questions :

1) is there an existing feature in AEM to do this ? 

2) if not, what is the easiest way to create such custom `Tag Library` ?

EDIT:

Assume that there is no ability to just include all component clientLibs, rather load only those that are added to the page.

Answer: 
There is no built in feature to do this. Although I've heard that the clientlib infrastructure is being looked at for a re-write so I'm optimistic that something like this will be added in the future.

We have, and I know other company have, created a "deferred script tag." Ours is a very simple tag that take a chunk of html like a clientlib include, add it to a unique list and then on an out call at the footer, spits it all out one after another.

Here's the core of a simple tag implementation that extends BodyTagSupport. Then in your footer grab the attribute and write it out. 

```
public int doEndTag() throws JspException {
    SlingHttpServletRequest request = (SlingHttpServletRequest)pageContext.getAttribute("slingRequest");

    Set<String> delayed = (Set<String>)request.getAttribute(DELAYED_INCLUDE);

    if(delayed == null){
        delayed = new HashSet<String>();
    }

    if(StringUtils.isNotBlank(this.bodyContent.getString())){
        delayed.add(this.bodyContent.getString().trim());
    }

    request.setAttribute(DELAYED_INCLUDE, delayed);
    return EVAL_PAGE;
}

```
Theoretically the possible way of doing is to write script in your page component/abstract page component that does something like this - 

Step1 : String path = currentPage.getPath()

Step2 : Query this path for components (one way is to have a master list do a contains clause on sling:resourceType)

Step 3: User resource resolver to resolve the resourceType in Step 3, this will give you resource under your apps.

Step 4: From the above resource get the sub-resource with primary type as cq:ClientLibraryFolder

Step 5: from the client libs resource in Step 4 get the categories and include the JS from them

you could actually write a model to adapt a component resource to a clientLibrary to actually clean the code.

Let me know if you need actual code, I can write that in my free time.