J3.x

Agregar JavaScript y CSS a la página

From Joomla! Documentation

Revision as of 18:56, 30 September 2015 by Abulafia (talk | contribs) (Created page with "De forma predeterminada, Joomla! incluirá automáticamente una versión comprimida y sin comprimir de los scripts dependiendo de si el modo de depuración está habilitado o...")
Cambio en la API

La API de los métodos JHtml::script() y JHtml::stylesheet() ha cambiado después de Joomla! 1.5 - funcionó pero ya no se utiliza en Joomla! 2.5 y el soporte para la antigua API fue eliminado en Joomla! 3.x

Insertar desde un Archivo

Para tener un documento HTML bien formateado, debes poner todas las referencias a los archivos Javascript y CSS dentro de la porción <head>. Ya que Joomla! genera todo el código HTML que tiene una página antes de la salida, es posible añadir estas referencias dentro de las etiquetas <head> desde la extensión. La forma más sencilla de hacer esto es hacer uso de la funcionalidad integrada en Joomla!.

JDocument

Esta es una opción mucho menos flexible. Sin embargo, es más eficiente para un gran número de escenarios tales como la inclusión de una hoja de estilos en una plantilla. Por supuesto, también tendrás que agregar manualmente el código de algunos de los pasos que se haría de forma automática utilizando el método JHtml siguiente.

En primer lugar, obtener una referencia al objeto del documento actual:

$document = JFactory::getDocument();

Luego para una hoja de estilos, usa este código:

$document->addStyleSheet($url);

Para agregar un archivo Javascript, utiliza este código:

$document->addScript($url);

donde $url es la variable que contiene la ruta de acceso completa al archivo javascript o CSS por ejemplo:
JUri::base() . 'templates/custom/js/sample.js'

Nota esto **NO** incluye Mootools o jQuery. Si el código requiere Mootools o jQuery mira Frameworks Javascript para más información sobre cómo incluirlos (nota jQuery sólo puede ser incluido de forma nativa en Joomla! 3.0+).

JHtml

JHtml ofrece mucha más flexibilidad que JDocument, mientras que utilizan la misma base de funcionalidad - de hecho, al final del camino se llama a JHtml JFactory::getDocument()->addStyleSheet() o JFactory::getDocument()->addScript().

Si sólo deseas incluir una ruta directa al archivo, en una plantilla por ejemplo, entonces es mejor usar JDocument. Sin embargo, si deseas tomar en cuenta que la depuración está habilitada para incluir un comprimido de secuencia de comandos o tomar ventaja de la plantilla con scripts y hojas de estilo reemplazables, a continuación, generalmente es mejor utilizar JHtml. Se recomienda a todos los Desarrolladores de 3ª Parte usar JHtml, para permitir sobrescribir su CSS y javascript de la plantilla por parte de los diseñadores de plantillas.

JHtml::script

La siguiente es la firma de esta función, puedes ver más en JHtml::script en api.joomla.org:

script(string $file, boolean $framework = false, boolean $relative = false, boolean $path_only = false, boolean $detect_browser = true, boolean $detect_debug = true) : mixed

El uso de JHtml para incluir un archivo javascript puede traer varios beneficios. El primero de ellos es que si el archivo javascript tiene una dependencia a mootools, a continuación, se puede incluir automáticamente mediante la configuración del segundo parámetro de este método, de la siguiente forma:

<?php
JHtml::script(JUri::base() . 'templates/custom/js/sample.js', true);
?>

El tercer parámetro de este método permite plantillas y archivos javascript reemplazables para permitir una mayor personalización de las extensiones. El primer parámetro ahora asume que estás comenzando en la carpeta JPATH_BASE/media - dentro de aquí puedes especificar el nombre de tu extensión, seguido por el nombre de tu archivo javascript. La ruta buscada es entonces JPATH_BASE/media/com_search/js/search.js para el siguiente fragmento de código JHtml.

<?php
JHtml::script('com_search/search.js', false, true);
?>

Nota el subdirectorio js que se busca dentro del directorio com_search no debe ser especificado en el método JHtml.

Sin embargo, en la parte superior de este si existe un archivo en js/com_search/search.js entonces esto va a ser incluidos en su lugar. Por ejemplo, digamos que una extensión tiene uan dependencia de mootools, pero el usuario sólo quiere qeu se cargue jQuery. Esto significa que un usuario podría reemplazar el archivo con la versión de jQuery.

De forma predeterminada, Joomla! incluirá automáticamente una versión comprimida y sin comprimir de los scripts dependiendo de si el modo de depuración está habilitado o no. Llama a tu script comprimido search.min.js y a la versión sin comprimir script-uncompressed.js o script.js para utilizar esta funcionalidad y la ayuda a la depuración de los scripts. Debes llamar a la función con la versión comprimida, como sigue:

<?php
JHtml::script('com_search/search.min.js');
?>

Furthermore you can include browser specific files. Joomla can look for the files of the following types

  • filename.ext
  • filename_browser.ext
  • filename_browser_major.ext
  • filename_browser_major_minor.ext

This can allow you to include internet explorer 6 specific files for example. By having a search.js for general use with a search_msie_6.js for a file with extra internet explorer 6 fixes.

JHtml::stylesheet

The following is the signature of this function, you can see more at JHtml::stylesheet on api.joomla.org:

Using JHtml to include a CSS file can bring you several benefits. The first of these is allowing template overridable CSS files to allow greater customization of extensions. Setting the third parameter to true now assumes you are starting in the JPATH_BASE/media folder - within here you specify your extension name followed by the name of your CSS file. The path searched is then JPATH_BASE/media/com_search/css/search.css for the following JHtml snippet.

<?php
JHtml::stylesheet('com_search/search.css', array(), true);
?>

Note the css subdirectory that is searched in the com_search directory shouldn't be specified in the JHtml method.

However on top of this if a file exists in css/com_search/search.css then this will be included instead. This allows people to customize the appearance of an extension to better match their templates styling.

Furthermore you can include browser specific files. Joomla can look for the files of the following types

  • filename.ext
  • filename_browser.ext
  • filename_browser_major.ext
  • filename_browser_major_minor.ext

This can allow you to include internet explorer 6 specific files for example. By having a search.css for general use with a search_msie_6.css for a file with extra internet explorer 6 fixes.

Similarly as with JHtml::script, if $detect_debug is true and you pass it a minified stylesheet example.min.css, when debug mode is on, the unminified stylesheet will be used instead, if it exists.

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', array(), true);
$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);