Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript inserted after the footer in SilverStripe

Why does my JavaScript appear after the footer? Below is my code in the layout (Page.ss):

<% include SideBar %>
<div class="content-container unit size3of4 lastUnit">
    <article>
    <h1>$Title</h1>
        <div class="content">
            <script type="text/javascript">
                window.onload = function() {
                    var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create });
                    function preload() {
                        game.load.image('logo', 'phaser.png');
                    }
                    function create() {
                        var logo = game.add.sprite(game.world.centerX, game.world.centerY, 'logo');
                        logo.anchor.setTo(0.5, 0.5);
                    }
                };
            </script>
        </div>
    </article>
    $Form
    $CommentsForm
</div>
like image 949
ssguest Avatar asked Aug 23 '15 16:08

ssguest


2 Answers

By default, SilverStripe includes all JavaScript files at the bottom of the page body. This is to allow all other site resources to load before any JavaScript is loaded.

If you have a script tag in a layout or include template it will move the script to the bottom of the body tag.

If you don't want the script tag to be moved you can set Requirements.write_js_to_body to false in your Page_Controller init() function:

class Page_Controller extends ContentController {

    public function init() {
        parent::init();

        Requirements::set_write_js_to_body(false);
    }

}

Note, this will move all your requirements included JavaScript files to the <head> tag.

like image 98
3dgoo Avatar answered Nov 17 '22 22:11

3dgoo


Another option if you want even more control is to use this: https://gist.github.com/markguinn/683ab8b22891632be6e5

Then add the following to Page_Controller::init or mysite/_config.php:

Requirements::set_backend(new BetterRequirementsBackend());

And add:

<!-- INSERT JS HERE -->

and

<!-- INSERT CSS HERE -->

to your template. This way you can control exactly where the injections happen. Note that you'll probably want to change line 23 to = false in the class above or override it in yaml config.

like image 41
Mark Guinn Avatar answered Nov 17 '22 21:11

Mark Guinn