osgi-bundleapache-felixsling

How to include JS in a page HTML with Apache Sling


In Apache Sling i want include a javascript into a HTML page. Via http://localhost:8080/bin/browser.html/ I created two nodes (then manually): html.html and processing.js.
JSON of html.html is:

{
  "jcr:created": "{Date}2018-04-19 20:50:09",
  "jcr:createdBy": "admin",
  "jcr:primaryType": "{Name}nt:file",
  "jcr:content": {
    "jcr:data": "/bin/cpm/nodes/property.bin/apps/res/html.html/_jcr_content?name=jcr%3Adata",
    "jcr:lastModified": "{Date}2018-04-19 20:50:09",
    "jcr:lastModifiedBy": "admin",
    "jcr:mimeType": "text/html",
    "jcr:primaryType": "{Name}nt:resource",
    "jcr:uuid": "ed3121b3-580c-46b2-acc6-7029cdb6f1c3"
  }
}

JSON of processing.js is:

{
  "jcr:data": "/bin/cpm/nodes/property.bin/apps/res/processing.js?name=jcr%3Adata",
  "jcr:lastModified": "{Date}2018-04-19 21:32:40",
  "jcr:lastModifiedBy": "admin",
  "jcr:mimeType": "text/javascript",
  "jcr:primaryType": "{Name}nt:resource",
  "jcr:uuid": "74fd137a-3b37-4893-b443-bd086a4fb4d7"
}

In page HTML I include processing.js with <script> tag in the <head> tag look like following:

<head>
    <script type="text/javascript" src="processing.js"></script>
</head>

Both nodes is located on the same path, that's "apps".

I get error in console of Mozilla Firefox:

Error Mozilla Firefoxhttp://i68.tinypic.com/a0cj88.png

In error.log file I get this error:

19.04.2018 22:13:32.813 *INFO* [0:0:0:0:0:0:0:1 [1524168812811] GET /apps/processing.js HTTP/1.1] org.apache.sling.engine.impl.SlingRequestProcessorImpl service: Resource /apps/processing.js not found

Why did I get this error? How can i fix it? Please help me. Thanks you very much in advance.


Solution

  • Try to add the resource path to the src of your file.

    <script type="text/javascript" src="${resource.path}/processing.js"></script>
    

    THat should solve the problem