Menu

The TPage class: javascript

Referencing .js files

The most indicated method to adding scripts to your page is to put all javascript code in separate .js files and then reference them in the head element of your page.

You can manipulate the js[] property pretty much the same way as you do with the css[] property, i.e., either as a string or as an array.

Examples:

<?php
//Adding two files to the already existing .js references in the page head
$page->js[] = 'somefunctions.js';
$page->js[] = 'someclass.js';
<?php
//Defining only two files to be added to the .js references in the page head; 
//previously added files, as well as the default .js files that are automatically 
//added, are removed.
$page->js = array('somefunctions.js', 'someclass.js');
<?php
//Using one single .js file:
$page->js = 'somefunctions.js';

Embedding javascript code

Instead of referencing external .js files, you can add scripts directly to the page head element. You can treat the script[] property either as a string or as an array.

<?php
$page->script[] = "var name = input('Please tell me your name: ');";
//or:
$page->script = "var name = input('Please tell me your name: ');";

Loading scripts after the page content

No matter how you add a script to a page, it will be inserted in the head element of the page, being loaded before the page content. To have these scripts be loaded after the page content, you can change the scriptsafter property of the page to true:

<?php
$page->js[] = 'somefunctions.js';
$page->script[] = "var name = input('Please tell me your name: ');";
$page->scriptsafter = true; // all references to .js files, as well as 
//embedded scripts, will now be loaded after all the page content has been rendered.
Posted by panglossa 2013-04-09 Labels: javascript page html TPage js js[] script

Log in to post a comment.