3

I have a module that is dependant on a couple of Javascript files.

How can I load these Javascript files on the front end when my module is called?

They are quite large so I cannot simply use an inline <script></script>

2
  • Do you mean on the front-end (when {exp:my_module} tags are used) or back-end (in you module's control panel)? Feb 1, 2013 at 13:09
  • The front-end, when the tags are used. Feb 1, 2013 at 13:14

1 Answer 1

6

I think you're looking for this page in the EE Developer docs.

Basically, if you only need the JS in the Control Panel (so not on the front-end of the site), put your JS files in the /your_addon_package/javascript/ folder and then use $this->EE->cp->load_package_js('my_file'); to load it.

If you need the JS outside of the CP as well, you need to put it in the /themes/third_party/your_addon_package/ folder and add a <script> tag to the header, if you want to use it in the CP.

If you want to output the JS file URL in your templates, create a method in your mod file that outputs URL_THIRD_THEMES.'your_addon/js/file.js' or something like that. Then use {exp:your_addon:your_method} to output the URL in the template.

7
  • I need it outwith the CP, so it will have to go in the themes folder. How do I then get the path to it for the <script> tag, without hard-coding the site URL? Feb 1, 2013 at 13:17
  • 3
    Use the URL_THIRD_THEMES constant (docs) (assuming you will be distributing your JS in the themes/third_party folder). Feb 1, 2013 at 13:24
  • EE->cp->add_to_head() cannot be used in the front end, as the CP class is unavailable. Feb 1, 2013 at 13:35
  • 2
    Correct, that's used when you have a JS file in the themes folder, but want to add it to the CP's head. If you want to generate the URL for templates, create a method in your mod file that outputs URL_THIRD_THEMES.'your_addon/js/file.js' or something like that. Then use {exp:your_addon:your_method} to output the URL in the template.
    – Low
    Feb 1, 2013 at 13:38
  • The benefit of doing what Low described vs say adding the js automatically to the head or footer like some other CMS do is that this allows you or other devs to place the js tag were ever we see fit and even conditionally at times to save on load which in this case sounds like is a good option being that you have "quite large" files.
    – Natetronn
    Feb 3, 2013 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.