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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With