Include JavaScript in Header or Footer

It's quite hard for a newbie to inject some JavaScript with elgg. I just spent hours trying to figure it out and failed. LOL! I know, I'm pathetic.

All I want to do is include some vanilla JavaScript which will open YouTube links in a lightbox. Typically, one could simply put this is the head:

<script src="myscript.js"></script>​

But, I get all kinds of errors. And after reading the docs I'm assuming this is because you can't add javascript the old school way like that in elgg. You have to AMD it, or whatever.

Maybe elgg just isn't the platform for me. It seems like it's developed for developers and not a casual web enthusiast. 

  • AMD modules have some advantages over the old way with script tags like performance, caching and dependency management. Loading a script with the script tag will block the page rendering until the script is loaded while AMD modules are loaded asyncronously. If your script requires other scripts to be loaded first, it's much easier to use AMD modules as you can explicitely defines the requirements and can then be sure the scripts are loaded in the right order. Using AMD modules is a bit tricky at first as you need to get used to the concept but it's not too difficult.

    If you add your script in your plugin for example in mod/my_plugin/views/default/js/my_plugin/my_script.js with the following basic structure:

    define(function(require) {
        var $ = require('jquery');
        var elgg = require('elgg');
    
        // here your js code
    
    }

    and then load the module with

    elgg_require_js('my_plugin/my_script');

    it should basically work. Where to put elgg_require_js() depends on the use case. If you only need it on a few pages or a single page, you would add the line of code in the view file that builts the content of this page. If you want to have it on many pages / all pages, you could just put the line in the init function in start.php of your plugin.

    The AMD module code example above assumes that your js code makes use of Elgg JS API functions and Jquery API functions. If this is not the case, you wouldn't have to require the 'jquery' and 'elgg' modules. As you mentioned "all kinds of errors" there might be some other requirements in your js code. I can't say for sure without knowing the code.

Beginning Developers

Beginning Developers

This space is for newcomers, who wish to build a new plugin or to customize an existing one to their liking