Difference between revisions of "Adding JavaScript and CSS to the page"
From Joomla! Documentation
Thelordofweb (talk | contribs) |
m |
||
Line 54: | Line 54: | ||
<translate><!--T:44--> | <translate><!--T:44--> | ||
− | Joomla! use special mechanism for "lazy loading" the options on the client side. It | + | Joomla! use special mechanism for "lazy loading" the options on the client side. It doesn't use inline JavaScript, that is good for page rendering speed, and make your site more friendly for the Speed Tester (eg Google).</translate> |
<translate><!--T:45--> | <translate><!--T:45--> |
Latest revision as of 07:30, 14 February 2018
Contents
Inserting from a File
To have a well-formed HTML document, you must put all references to Javascript and CSS files within the <head>
portion. Since Joomla! generates all the HTML that makes up a page before output, it is possible to add these references within the <head> tags from your extension. The simplest way to do this is to make use of the functionality built in to Joomla.
JDocument
First, get a reference to the current document object:
$document = JFactory::getDocument();
Then for a stylesheet, use this code:
$document->addStyleSheet($url);
To add a Javascript file, use this code:
$document->addScript($url);
where $url
is the variable containing the full path to the javascript or CSS file for example: JUri::base() . 'templates/custom/js/sample.js'
Note this will **NOT** include Mootools or jQuery. If your script requires Mootools or jQuery see Javascript Frameworks for full details on how to include them (note jQuery can only be included natively on Joomla! 3.0+).
It used to be possible to do this with JHTML, however, this was deprecated in Joomla 2.5 and removed in Joomla 3.x.
Adding the options to your JavaScript code
Beside adding inline scripts, Joomla! provide mechanism to store the options in the "optionsStorage". This is allowed to nicely manage an existing options on the server side and on the client side. And allow to place all JavaScript logic to the JavaScript file, that will be cached by browser.
Joomla! use special mechanism for "lazy loading" the options on the client side. It doesn't use inline JavaScript, that is good for page rendering speed, and make your site more friendly for the Speed Tester (eg Google).
Thus use "optionsStorage" preferred, than use inline JavaScript to add the script options.
Example of use
Add the script options to your module:
$document = JFactory::getDocument();
$document->addScriptOptions('mod_example', array(
'colors' => array('selector' => 'body', 'color' => 'orange'),
'sliderOptions' => array('selector' => '.my-slider', 'timeout' => 300, 'fx' => 'fade')
));
Access to your options on the client side:
var myOptions = Joomla.getOptions('mod_example');
console.log(myOptions.colors); // Print in the browser console your options
console.log(myOptions.sliderOptions);
Override the options on server side (possible until the head rendering):
$document = JFactory::getDocument();
// Get existing options
$myOptions = $document->getScriptOptions('mod_example');
// Change the value
$myOptions['colors'] = array('selector' => 'body', 'color' => 'green');
// Set new options
$document->addScriptOptions('mod_example', $myOptions);
Inserting inline scripts from within a PHP file
If your Javascript or CSS are generated using PHP, you can add the script or stylesheet directly into the head of your document:
$document = JFactory::getDocument();
// Add Javascript
$document->addScriptDeclaration('
window.event("domready", function() {
alert("An inline JavaScript Declaration");
});
');
// Add styles
$style = 'body {'
. 'background: #00ff00;'
. 'color: rgb(0,0,255);'
. '}';
$document->addStyleDeclaration($style);
Javascript Example
For example, the following code is used to define a custom tool tip that takes advantage of mootools.
function getToolTipJS($toolTipVarName, $toolTipClassName){
$javascript = 'window.addEvent(\"domready\", function(){' ."\n";
$javascript .= "\t" .'var $toolTipVarName = new Tips($$("' . $toolTipVarName .'"), {' ."\n";
$javascript .= "\t\t" .'className: "' .$toolTipClassName .'",' ."\n";
$javascript .= "\t\t" .'initialize: function(){' ."\n";
$javascript .= "\t\t\t" .'this.fx = new Fx.Style(this.toolTip, "opacity", {duration: 500, wait: false}).set(0);' ."\n";
$javascript .= "\t\t" .'},' ."\n";
$javascript .= "\t\t" .'onShow: function(toolTip){' ."\n";
$javascript .= "\t\t\t" .'this.fx.start(1);' ."\n";
$javascript .= "\t\t" .'},' ."\n";
$javascript .= "\t\t" .'onHide: function(toolTip) {' ."\n";
$javascript .= "\t\t\t" .'this.fx.start(0);' ."\n";
$javascript .= "\t\t" .'}' ."\n";
$javascript .= "\t" .'});' ."\n";
$javascript .= '});' ."\n\n";
return $javascript;
}
$document = JFactory::getDocument();
$document->addStyleSheet("/joomla/components/com_mycustomcomponent/css/mytooltip.css",'text/css',"screen");
$document->addScriptDeclaration(getToolTipJS("mytool","MyToolTip"));
Note that in order for this Javascript to be functionally useful, it would be necessary to include the appropriate class name in the HTML, as well as providing the mytooltip.css
file. Both are outside the scope of this article.
CSS Examples
This is also useful if your inserting a form field of CSS into your code. For example in a module, you might want a user to choose to call the colour of the border. After calling the form fields value and assigning it a variable $bordercolor in mod_example.php. Then in tmpl/default.php you can include the following:
$document = JFactory::getDocument();
$document->addStyleSheet('mod_example/mod_example.css');
$style = '#example {
border-color:#' . $bordercolor . ';
}';
$document->addStyleDeclaration( $style );
Here mod_example.css contains the CSS file of any non-parameter based styles. Then the bordercolor parameter/form field is added in separately.
Add Custom Tag
There will be some occasions where even these functions are not flexible enough, as they are limited to writing the contents of <script />
or <style />
tags, and cannot add anything outside those tags. One example would be the inclusion of a stylesheet link within conditional comments, so that it is picked up only by Internet Explorer 6 and earlier. To do this, use $document->addCustomTag
:
$stylelink = '<!--[if lte IE 6]>' ."\n";
$stylelink .= '<link rel="stylesheet" href="../css/IEonly.css" />' ."\n";
$stylelink .= '<![endif]-->' ."\n";
$document = JFactory::getDocument();
$document->addCustomTag($stylelink);
If it was necessary to include other conditional CSS, always include the "addCustomTag" method after declare it.