JavaScript inserted after footer in SilverStripe

Why is my JavaScript appearing after the footer? Below is my code in 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> 
+6
source share
2 answers

By default, SilverStripe includes all JavaScript files at the bottom of the page body. This allows you to load all other site resources before loading any JavaScript.

If you have a script tag in the layout or include a template, it moves the script to the end of the body tag.

If you do not want the script tag to be moved, you can set Requirements.write_js_to_body to false in Page_Controller init() :

 class Page_Controller extends ContentController { public function init() { parent::init(); Requirements::set_write_js_to_body(false); } } 

Please note that all your requirements will be included in the JavaScript files in the <head> .

+3
source

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 --> 

into your template. This way you can precisely control where the injection is. Note that you probably want to change line 23 to = false in the class above or override it in yaml configuration.

+1
source

All Articles