2012-09-16 5 views

Odpowiedz

11

To zależy od tego, gdzie dokładnie chcesz zadeklarować ratunek. Normalnie, jedynym powodem, dla którego można je programowo zadeklarować, jest niestandardowy kod UIComponent lub Renderer, który generuje kod HTML, który z kolei wymaga tych zasobów JS i/lub CSS. Następnie muszą one zostać zadeklarowane przez @ResourceDependency lub @ResourceDependencies.

@ResourceDependency(library="mylibrary", name="foo.css") 
public class FooComponentWithCSS extends UIComponentBase { 
    // ... 
} 
@ResourceDependencies({ 
    @ResourceDependency(library="mylibrary", name="bar.css"), 
    @ResourceDependency(library="mylibrary", name="bar.js") 
}) 
public class BarComponentWithCSSandJS extends UIComponentBase { 
    // ... 
} 

Ale jeśli naprawdę trzeba zadeklarować je gdzie indziej, na przykład w sposobie podkład fasoli który wywołał przed renderowanie odpowiedzi (w przeciwnym razie jest to po prostu zbyt późno), to można to zrobić przez UIViewRoot#addComponentResource(). Zasób komponentu musi być utworzony jako UIOutput mający typ renderera javax.faces.resource.Script lub javax.faces.resource.Stylesheet, reprezentujący odpowiednio pełną wartość: <h:outputScript> lub <h:outputStylesheet>. Atrybuty library i name można po prostu umieścić w mapie atrybutów.

UIOutput css = new UIOutput(); 
css.setRendererType("javax.faces.resource.Stylesheet"); 
css.getAttributes().put("library", "mylibrary"); 
css.getAttributes().put("name", "bar.css"); 

UIOutput js = new UIOutput(); 
js.setRendererType("javax.faces.resource.Script"); 
js.getAttributes().put("library", "mylibrary"); 
js.getAttributes().put("name", "bar.js"); 

FacesContext context = FacesContext.getCurrentInstance(); 
context.getViewRoot().addComponentResource(context, css, "head"); 
context.getViewRoot().addComponentResource(context, js, "head"); 
+1

Tutaj znajdziesz informacje gdzie umieścić deklarację: http://stackoverflow.com/questions/3586629 – Thor

+0

Świetnie! To uratowało mój dzień. –

+0

Ja także borykałem się z tym, gdzie dodać deklarację. Skończyło się na dodaniu go do konstruktora mojego UIComponent. –

2

Możesz dodać skrypt i styl zasobów strony tak:

var head = document.getElementsByTagName("head")[0]; 
var s = document.createElement("script"); 
s.type = "text/javascript"; 
s.src = "xxxx.js"; 
head.appendChild(s); 

s = document.createElement("style"); 
s.type = "text/css" 
s.src = "yyy.css"; 
head.appendChild(s); 

Albo w postaci funkcji:

function addScript(path) { 
    var head = document.getElementsByTagName("head")[0]; 
    var s = document.createElement("script"); 
    s.type = "text/javascript"; 
    s.src = path; 
    head.appendChild(s); 
} 

function addCSSFile(path) { 
    var head = document.getElementsByTagName("head")[0]; 
    var s = document.createElement("style"); 
    s.type = "text/css"; 
    s.src = path; 
    head.appendChild(s); 
} 
+0

Chociaż jest to poprawne, gdy jest używane w JavaScript, nie pomaga to w kontekście JSF. –