3

I want to access a JSF resources ( under WebPages/resources/img) from a javascript function like:

function hideSpinner() {
    arguments[i].poster = './img/sppiner.png';
}

I have tried arguments[i].poster = "${resource['img/sppiner.png']}"; and arguments[i].poster = '${resource[\'img/sppiner.png\']}'; but it doesnt work..

What Can I do?

RoberV
  • 587
  • 5
  • 22
  • Try `#{request.contextPath}/resources/img/sppiner.png`. It will work if your javascript function is located into a facelet page. – Aritz May 08 '15 at 18:51

1 Answers1

4

EL expressions are only evaluated in Facelets (XHTML) files and in CSS files loaded via <h:outputStylesheet>. They are not evaluated in JS files loaded via <h:outputScript>.

You basically need to render an inline script which sets a (global) JavaScript variable which the JS file should in turn refer to.

<h:outputScript>var spinnerImage = "${resource['img/sppiner.png']}";</h:outputScript>
<h:outputScript name="js/some.js" />
arguments[i].poster = spinnerImage;

Much cleaner, however, is to set the image as a CSS background image associated with a specific CSS style class and then just let JavaScript set that style class on the desired element. As said, you can use EL expressions in CSS files loaded via <h:outputStylesheet>. See also a.o. How to reference JSF image resource as CSS background image url.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • great answer, if the file js/some.js has javascript file references then these return 404 error as they are not referenced in the h:outputScript way, do you have any idea how to resolve without updating all references in js/some.js? – ScottFree Jan 21 '20 at 23:41