开发者

Include JS files based on current page

I have the following on my main jsf wrapper page:

<head>
  <meta http-equiv="Content-Type" content="text/xhtml; charset=UTF-8"/>
  <title>
    <ui:insert name="pageTitle" /> 
  </title>

  <a4j:loadScript src="resource://jquery.js" />
  <a4j:loadScript src="resource:///bla/html/js/base.js" />
  <a4j:loadScript src="resource:///bla/html/js/common.js" />
  <a4j:loadScript src="resource:///bla/html/js/inactivity.js" />
</head>

Now I have a new page on the site and it 开发者_运维知识库requires some js functions. So i have created a new js file, myNewJSFile.js

I only want it loaded if a user lands on this page so obviosuly I dont want to add it to my above list of files in the head. Additionally I'd rather not include it at the top of my new page.

What I want is one place where I can define what files to load based on the current page.

So somthing like this (Pseudo code):

main jsf wrapper:

<head>
  <jsIncludes>
</head>

jsIncludes file:

<a4j:loadScript src="resource://jquery.js" />
<a4j:loadScript src="resource:///bla/html/js/base.js" />
<a4j:loadScript src="resource:///bla/html/js/common.js" />
<a4j:loadScript src="resource:///bla/html/js/inactivity.js" />

<if page == "myNewPage>
  <a4j:loadScript src="resource:///bla/html/js/myNewJsFile.js" />
<elfeif ...>
...
</if>

Is there a simple way of doing this?

Thanks


a4j:loadScript always places the javascript in the <head>, no matter where you use it, you have to do nothing. (the doc doesn't mention this for some strange reason)

So to answer your question: if you use <a4j:loadScript src="resource:///bla/html/js/myNewJsFile.js" /> in the page where you need it, the <script style="text/javascript" src="..." /> will appear in the <head>.


I'd rather add another <ui:insert> to the <head> of the main template.

<head>
    ...
    <ui:insert name="headContent" />
</head>

Then in the page template, just define the additional script to be inserted there.

<ui:composition template="main.xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:a4j="http://??? can't tell from top of head :)"
>
    <ui:define name="headContent">
        <a4j:loadScript src="resource:///bla/html/js/myNewJsFile.js" />
    </ui:define>

    ...
</ui:composition>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜