J3.x

Adding JavaScript and CSS to the page/es: Difference between revisions

From Joomla! Documentation

Created page with "Ten en cuenta que para que este Javascript sea funcionalmente útil, sería necesario incluir el nombre de clase apropiado en el archivo HTML, así como proporcionar el archiv..."
Created page with "Se pueden añadir los parámetros <tt>$options</tt> y <tt>$attributes</tt> a los anterior métodos. <tt>$options</tt> controla cómo los elementos <tt><script></tt> y <tt><lin..."
 
(31 intermediate revisions by 4 users not shown)
Line 1: Line 1:
<noinclude><languages /></noinclude>
<noinclude><languages /></noinclude>
{{notice|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|title=Cambio en la API}}
Esta es una de las series de [[API Guides]], con el objetivo de ayudar a entender cómo usar la API de Joomla a proveyendo explicaciones detallasdas y código de ejemplo que puedas instalar y ejecutar fácilmente.


== Insertar desde un Archivo ==
== 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 <code><head></code>. 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===
Joomla permite añadir archivos Javascript y CSS a tu documento HTML y ubica los elementos <tt><script></tt> y <tt><link></tt> asociados en la sección de cabecera HTML <tt><head></tt>. Para hacer esto se llama a los métodos <tt>addScript</tt> y <tt>addStyleSheet</tt> del objeto Joomla que representa el documento HTML. Desde Joomla! se almacenan todos los datos HTML relacionados que dibujan una página antes de la salida. Es posible llamar a estos métodos en cualquier lugar de tu código.  
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:
En primer lugar, obtener una referencia al objeto del documento actual:


<source lang="php">
<source lang="php">
$document = JFactory::getDocument();
use Joomla\CMS\Factory;
$document = Factory::getDocument();
// above 2 lines are equivalent to the older form: $document = JFactory::getDocument();
</source>
</source>


Line 20: Line 20:
</source>
</source>


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


<source lang="php">
<source lang="php">
Line 26: Line 26:
</source>
</source>


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


Nota esto **NO** incluye ''Mootools'' o ''jQuery''. Si el código requiere ''Mootools'' o ''jQuery'' mira [[S:MyLanguage/Javascript_Frameworks|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+).
Nota esto **NO** incluye ''Mootools'' o ''jQuery''. Si el código requiere ''Mootools'' o ''jQuery'' mira [[S:MyLanguage/Javascript_Frameworks|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+).
Era usual hacer esto con JHTML, sin embargo, está obsoleto en Joomla 2.5 y fue eliminado en Joomla 3.x.


===JHtml===
=== Parámetros $options y $attributes ===
''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'' <code>JFactory::getDocument()->addStyleSheet()</code> o <code>JFactory::getDocument()->addScript()</code>.
Se pueden añadir los parámetros <tt>$options</tt> y <tt>$attributes</tt> a los anterior métodos. <tt>$options</tt> controla cómo los elementos <tt><script></tt> y <tt><link></tt> salen mientras que <tt>$attributes</tt> establece los atributos HTML de estas etiquetas. (Nótese que that aunque hay marcadores obsoletos en los métodos addScript y addStyleSheet del [https://api.joomla.org/cms-3/classes/Joomla.CMS.Document.Document.html#method_addScript Documento Joomla API], estos marcadores se refieren a la firma de estos métodos; el formulario de la firma usando los parámetro <tt>$options</tt> y <tt>$attributes</tt> no está obsoleto).
 
The <tt>$options</tt> parameter should be an array, and 2 different options are currently supported:
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.
* <tt>'version' => 'auto'<tt> If this is set then a "media version" is appended as a query parameter to the CSS or JS URL within the <tt><script></tt> or <tt><link></tt> element. This is a string (an md5 hash) which is generated from factors including the Joomla version, your Joomla instance <tt>secret</tt> and the date/time at which the media version was generated. The media version is regenerated whenever anything is installed on the Joomla instance, and its purpose is to force browsers to then reload the CSS and JS files instead of using possibly outdated versions from cache.
 
Por ejemplo:
====JHtml::script====
 
La siguiente es la firma de esta función, puedes ver más en [https://api.joomla.org/cms-3/classes/JHtml.html#method_script JHtml::script en api.joomla.org]:
 
<source lang="php">
<source lang="php">
script(string $file, boolean $framework = false, boolean $relative = false, boolean $path_only = false, boolean $detect_browser = true, boolean $detect_debug = true) : mixed</source>
$document->addStyleSheet("...demo.css", array('version'=>'auto'));
 
// leads to something like
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:
// <link href="...demo.css?37e343bbb4073e0dfe5b1eb40b6" rel="stylesheet">
 
</source>
The string of characters after the ? is the md5 hash, which will change when extensions or Joomla itself are installed/upgraded/deinstalled.
* <tt>'conditional' => 'lt IE 9'</tt> (as an example). This outputs the <tt><script></tt> or <tt><link></tt> within a [https://en.wikipedia.org/wiki/Conditional_comment Conditional Comment] which earlier versions of Internet Explorer interpreted.
For example
<source lang="php">
<source lang="php">
<?php
$document->addScript("...demo.js", array('conditional'=>'lt IE 9'));
JHtml::script(JUri::base() . 'templates/custom/js/sample.js', true);
// leads to
?>
// <!--[if lt IE 9]><script src="...demo.js"></script><![endif]-->
</source>
</source>
 
The <tt>$attributes</tt> parameter should also be an array, and these are mapped to be html attributes of the <tt><script></tt> or <tt><link></tt> element. For example,
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 <code>JPATH_BASE/media</code> - dentro de aquí puedes especificar el nombre de tu extensión, seguido por el nombre de tu archivo javascript. La ruta buscada es entonces <code>JPATH_BASE/media/com_search/js/search.js</code> para el siguiente fragmento de código ''JHtml''.


<source lang="php">
<source lang="php">
<?php
$document->addScript("...demo.js", array(), array('async'=>'async'));
JHtml::script('com_search/search.js', false, true);
// leads to
?>
// <script src="...demo.js" async></script>
</source>
</source>
== Agregar opciones a tu código JavaScript ==
{{Joomla version|version=3.7|time=and after|comment=Solo disponible en Joomla! 3.7 y superior|align=left}}
(Note that these Options are different from the <tt>$options</tt> parameter described above).
Además de agregar scripts, Joomla! ofrece un mecanismo para almacenar las opciones en "optionsStorage".
Esto permite administrar las opciones existentes en el lasdo del servidor y en el cliente. Esto permite ubicar toda la lógica de JavaScript en el archivo JavaScript, el cual se agrega al caché del navegador.


Nota el subdirectorio ''js'' que se busca dentro del directorio ''com_search''  no debe ser especificado en el método ''JHtml''.
Joomla! utiliza un mecanismo especial para aplicar "lazy loading" en las opciones del lado cliente. No utiliza JavaScript inline, lo cual es mejor para la velocidad de renderización de la página, y hace el sitio web más amigable para un verificador de velocidad (ej. Google).


Sin embargo, en la parte superior de este si existe un archivo en <code>js/com_search/search.js</code> 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.
Es mejor usar "optionsStorage" que JavaScript inline para agregar las opciones del script.


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:
"'Ejemplo de uso"'


Agregar las opciones del script a tu módulo:
<source lang="php">
<source lang="php">
<?php
$document = JFactory::getDocument();
JHtml::script('com_search/search.min.js');
$document->addScriptOptions('mod_example', array(
?>
    'colors' => array('selector' => 'body', 'color' => 'orange'),
    'sliderOptions' => array('selector' => '.my-slider', 'timeout' => 300, 'fx' => 'fade')
));
</source>
</source>


Además puedes incluir explorar archivos específicos. Joomla! puede buscar archivos de los siguientes tipos
Acceso a tus opciones en el lado del cliente:
* nombre_de_archivo.ext
<source lang="javascript">
* nombre_de_archivo_browser.ext
var myOptions = Joomla.getOptions('mod_example');
* nombre_de_archivo_browser_major.ext
console.log(myOptions.colors); // Print your options in the browser console.
* nombre_de_archivo_browser_major_minor.ext
console.log(myOptions.sliderOptions);
 
</source>
Esto puede permitir incluir archivos específicos de internet explorer 6, por ejemplo. Por tener un search.js para uso general con una search_msie_6.js para un archivo adicional con las correcciones de internet explorer 6.
 
====JHtml::stylesheet====
 
La siguiente es la firma de esta función, puedes ver más en [https://api.joomla.org/cms-3/classes/JHtml.html#method_stylesheet JHtml::stylesheet en api.joomla.org]:
 
El uso de JHtml para incluir un archivo CSS puede traer varios beneficios. El primero de ellos es que permite plantillas con archivos CSS reemplazables, para permitir una mayor personalización de las extensiones. Ajusta el tercer parámetro a ''true'', ahora se supone que estás comenzando en la carpeta <code>JPATH_BASE/media</code> dentro de aquí puedes especificar el nombre de tu extensión, seguido por el nombre de tu archivo CSS. La ruta buscada es entonces <code>JPATH_BASE/media/com_search/css/búsqueda.css</code> para el siguiente fragmento de código ''JHtml''.


Sobreescribir las opciones en el lado servidor (lo cual es posible hasta la renderización del "head"):
<source lang="php">
<source lang="php">
<?php
$document  = JFactory::getDocument();
JHtml::stylesheet('com_search/search.css', array(), true);
// 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);
</source>
</source>


Nota el subdirectorio <code>css</code> que se busca dentro del directorio <code>com_search</code>  no debe ser especificado en el método ''JHtml''.
== Passing language strings to Javascript ==
There are cases when you may want to output an error message in your JavaScript code and want to use the Joomla mechanism of language strings. You could manage this by using addScriptOptions to pass down each language string you need, but Joomla provides a more succint solution.
To pass a language string to JavaScript do in your PHP code, for example,


Sin embargo, en la parte superior de este si existe un archivo en <code>css/com_search/search.css</code> entonces este va a ser incluidos en su lugar. Esto permite a las personas personalizar la apariencia de una extensión para adaptarse mejor al estilo de sus plantillas.
<tt>JText::script('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN');</tt>
Then in your JavaScript code you can do:


Además puedes incluir explorar archivos específicos. Joomla! puede buscar archivos de los siguientes tipos
<tt>var message = Joomla.JText._('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN');</tt>
* nombre_de_archivo.ext
to obtain in the user's language the text message associated with the language constant.
* nombre_de_archivo_browser.ext
Obviously certain language strings have embedded %s characters, so in your JavaScript code you will have to handle that, eg using an external JavaScript sprintf library or string replace, etc.
* nombre_de_archivo_browser_major.ext
* nombre_de_archivo_browser_major_minor.ext
 
Esto puede permitir incluir archivos específicos de internet explorer 6, por ejemplo. Por tener un search.js para uso general con una search_msie_6.js para un archivo adicional con las correcciones de internet explorer 6.
 
Del mismo modo como con ''JHtml::script'', si $detect_debug es verdadero y pasas una hoja de estilo minimizada ejemplo.min.css, cuando el modo de depuración está activado, la hoja no minimizada, si es que existe, será usada en su lugar.  


== Insertar secuencias de comandos en línea desde dentro de un archivo PHP ==
== Insertar secuencias de comandos en línea desde dentro de un archivo PHP ==
Line 126: Line 129:
</source>
</source>


<div class="mw-translate-fuzzy">
=== Ejemplo de Javascript ===
=== Ejemplo de Javascript ===
Por ejemplo, el siguiente código se utiliza para definir un texto de ayuda emergente personalizado que toma ventaja de mootools.
Por ejemplo, el siguiente código se utiliza para definir un texto de ayuda emergente personalizado que toma ventaja de mootools.
</div>
For example, the following code is used to define a custom tool tip that takes advantage of Mootools.


<source lang="php">
<source lang="php">
Line 153: Line 159:
</source>
</source>


<div class="mw-translate-fuzzy">
Ten en cuenta que para que este Javascript sea funcionalmente útil, sería necesario incluir el nombre de clase apropiado en el archivo HTML, así como proporcionar el archivo <code>mytooltip.css</code>. Ambos están fuera del alcance de este artículo.
Ten en cuenta que para que este Javascript sea funcionalmente útil, sería necesario incluir el nombre de clase apropiado en el archivo HTML, así como proporcionar el archivo <code>mytooltip.css</code>. Ambos están fuera del alcance de este artículo.
</div>


=== CSS Examples ===
=== Ejemplos de CSS ===
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:
<div class="mw-translate-fuzzy">
Esto también es útil si tu insertas un campo de formulario de CSS en el código. Por ejemplo, en un módulo, puedes ser que desees que un usuario pueda elegir el color del borde. Después de llamar al avlro de los campos de formulario y asignarlo a una variable $bordercolor en mod_example.php. A continuación, en tmpl/default.php se puede incluir lo siguientes:
</div>


<source lang="php">
<source lang="php">
$document = JFactory::getDocument();
$document = JFactory::getDocument();
$document->addStyleSheet('mod_example/mod_example.css', array(), true);
$document->addStyleSheet('mod_example/mod_example.css');
$style = '#example {
$style = '#example {
border-color:#' . $bordercolor . ';
border-color:#' . $bordercolor . ';
Line 166: Line 176:
$document->addStyleDeclaration( $style );
$document->addStyleDeclaration( $style );
</source>
</source>
 
Aquí mod_example.css contiene el archivo CSS de cualquier no-parámetro base de estilos. A continuación, el parámetro bordercolor/campo de formulario se agrega por separado.
Here mod_example.css contains the CSS file of any non-parameter based styles. Then the bordercolor parameter/form field is added in separately.
==Agregar Etiqueta Personalizada==
 
Habrá algunas ocasiones en las que incluso estas funciones no son lo suficientemente flexibles, ya que están limitadas a escribir el contenido de las etiquetas <code><script /></code> o <code><style /></code>, y no se puede agregar nada fuera de esas etiquetas. Un ejemplo sería la inclusión de un enlace a hojas de estilos dentro de los comentarios condicionales, que son recogidos únicamente por Internet Explorer 6 y anteriores. Para hacer esto, usa <code>$document->addCustomTag</code>:
==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 <code><script /></code> or <code><style /></code> 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 <code>$document->addCustomTag</code>:


<source lang="php">
<source lang="php">
Line 179: Line 187:
$document = JFactory::getDocument();
$document = JFactory::getDocument();
$document->addCustomTag($stylelink);
$document->addCustomTag($stylelink);
</source>
If it was necessary to include other conditional CSS, always include the "addCustomTag" method after it is declared.
== Sample Module Code ==
Below is the code for a simple Joomla module which you can install and run to demonstrate adding CSS and JavaScript, and can adapt to experiment with the concepts above. If you are unsure about development and installing a Joomla module then following the tutorial at [[S:MyLanguage/J3.x:Creating a simple module/Introduction| Creating a simple module ]] will help.
In a folder mod_css_js_demo create the following 4 files:
<tt>mod_css_js_demo.xml</tt>
<source lang="xml">
<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1" client="site" method="upgrade">
    <name>css js demo</name>
    <version>1.0.1</version>
    <description>Code for including JS and CSS links</description>
    <files>
        <filename module="mod_css_js_demo">mod_css_js_demo.php</filename>
<filename>demo.css</filename>
<filename>demo.js</filename>
    </files>
</extension>
</source>
<tt>mod_css_js_demo.php</tt>
<source lang="php">
<?php
defined('_JEXEC') or die('Restricted Access');
use Joomla\CMS\Factory;
$document = Factory::getDocument();
$options = array("version" => "auto");
$attributes = array("defer" => "defer");
$document->addScript(JURI::root() . "modules/mod_css_js_demo/demo.js", $options, $attributes);
$document->addStyleSheet(JURI::root() . "modules/mod_css_js_demo/demo.css", $options);
$document->addScriptOptions('my_vars', array('id' => "css-js-demo-id2"));
JText::script('JLIB_HTML_EDIT_MENU_ITEM_ID');
echo '<h1 id="css-js-demo-id1">Hello World!</h3>';
echo '<button id="css-js-demo-id2">Click here!</button>';
</source>
<tt>demo.css</tt>
<source lang="css">
#css-js-demo-id1 {
color: red;
}
</source>
<tt>demo.js</tt>
<source lang="JavaScript">
jQuery(document).ready(function() {
   
const params = Joomla.getOptions('my_vars');
console.log(params);
console.log("JS language constant: " + Joomla.JText._('JLIB_HTML_EDIT_MENU_ITEM_ID'));
var message = Joomla.JText._('JLIB_HTML_EDIT_MENU_ITEM_ID');
message = message.replace("%s", params.id);
document.getElementById(params.id).addEventListener("click", function() {alert(message);});
});
</source>
</source>
Zip up the mod_css_js_demo directory to create <tt>mod_css_js_demo.zip</tt>.
Within your Joomla administrator go to Install Extensions and via the Upload Package File tab select this zip file to install this sample mod_css_js_demo module.
Make this module visible by editing it (click on it within the Modules page) then:
# making its status Published
# selecting a position on the page for it to be shown
# on the menu assignment tab specify the pages it should appear on
When you visit a site web page then you should see the module in your selected position, and it should display
* a message Hello World! which the CSS file should change to display in red
* a button which when you click it will execute an <tt>alert()</tt> showing the language string and variable which were passed down from the PHP code.
Using your browser's development tools you can also view the <tt><script></tt> and <tt><link></tt> elements within the HTML and see the JavaScript output on the console.


<noinclude>
<noinclude>
[[Category:Development/es|Desarrollo]]
[[Category:Development/es]]
[[Category:Tutorials]]
[[Category:Tutorials/es]]
[[Category:Component Development]]
[[Category:Component Development/es]]
[[Category:Module Development]]
[[Category:Module Development/es]]
[[Category:JavaScript]]
[[Category:JavaScript/es]]
[[Category:CSS]]
[[Category:CSS/es]]
</noinclude>
</noinclude>

Latest revision as of 10:28, 13 March 2021

Esta es una de las series de API Guides, con el objetivo de ayudar a entender cómo usar la API de Joomla a proveyendo explicaciones detallasdas y código de ejemplo que puedas instalar y ejecutar fácilmente.

Insertar desde un Archivo

Joomla permite añadir archivos Javascript y CSS a tu documento HTML y ubica los elementos <script> y <link> asociados en la sección de cabecera HTML <head>. Para hacer esto se llama a los métodos addScript y addStyleSheet del objeto Joomla que representa el documento HTML. Desde Joomla! se almacenan todos los datos HTML relacionados que dibujan una página antes de la salida. Es posible llamar a estos métodos en cualquier lugar de tu código.

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

use Joomla\CMS\Factory;
$document = Factory::getDocument();
// above 2 lines are equivalent to the older form: $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+). Era usual hacer esto con JHTML, sin embargo, está obsoleto en Joomla 2.5 y fue eliminado en Joomla 3.x.

Parámetros $options y $attributes

Se pueden añadir los parámetros $options y $attributes a los anterior métodos. $options controla cómo los elementos <script> y <link> salen mientras que $attributes establece los atributos HTML de estas etiquetas. (Nótese que that aunque hay marcadores obsoletos en los métodos addScript y addStyleSheet del Documento Joomla API, estos marcadores se refieren a la firma de estos métodos; el formulario de la firma usando los parámetro $options y $attributes no está obsoleto). The $options parameter should be an array, and 2 different options are currently supported:

  • 'version' => 'auto' If this is set then a "media version" is appended as a query parameter to the CSS or JS URL within the <script> or <link> element. This is a string (an md5 hash) which is generated from factors including the Joomla version, your Joomla instance secret and the date/time at which the media version was generated. The media version is regenerated whenever anything is installed on the Joomla instance, and its purpose is to force browsers to then reload the CSS and JS files instead of using possibly outdated versions from cache.

Por ejemplo:

$document->addStyleSheet("...demo.css", array('version'=>'auto'));
// leads to something like
// <link href="...demo.css?37e343bbb4073e0dfe5b1eb40b6" rel="stylesheet">

The string of characters after the ? is the md5 hash, which will change when extensions or Joomla itself are installed/upgraded/deinstalled.

  • 'conditional' => 'lt IE 9' (as an example). This outputs the <script> or <link> within a Conditional Comment which earlier versions of Internet Explorer interpreted.

For example

$document->addScript("...demo.js", array('conditional'=>'lt IE 9'));
// leads to
// <!--[if lt IE 9]><script src="...demo.js"></script><![endif]-->

The $attributes parameter should also be an array, and these are mapped to be html attributes of the <script> or <link> element. For example,

$document->addScript("...demo.js", array(), array('async'=>'async'));
// leads to
// <script src="...demo.js" async></script>

Agregar opciones a tu código JavaScript

Joomla! 
≥ 3.7
Solo disponible en Joomla! 3.7 y superior

(Note that these Options are different from the $options parameter described above).

Además de agregar scripts, Joomla! ofrece un mecanismo para almacenar las opciones en "optionsStorage". Esto permite administrar las opciones existentes en el lasdo del servidor y en el cliente. Esto permite ubicar toda la lógica de JavaScript en el archivo JavaScript, el cual se agrega al caché del navegador.

Joomla! utiliza un mecanismo especial para aplicar "lazy loading" en las opciones del lado cliente. No utiliza JavaScript inline, lo cual es mejor para la velocidad de renderización de la página, y hace el sitio web más amigable para un verificador de velocidad (ej. Google).

Es mejor usar "optionsStorage" que JavaScript inline para agregar las opciones del script.

"'Ejemplo de uso"'

Agregar las opciones del script a tu módulo:

$document = JFactory::getDocument();
$document->addScriptOptions('mod_example', array(
    'colors' => array('selector' => 'body', 'color' => 'orange'),
    'sliderOptions' => array('selector' => '.my-slider', 'timeout' => 300, 'fx' => 'fade')
));

Acceso a tus opciones en el lado del cliente:

var myOptions = Joomla.getOptions('mod_example');
console.log(myOptions.colors); // Print your options in the browser console.
console.log(myOptions.sliderOptions);

Sobreescribir las opciones en el lado servidor (lo cual es posible hasta la renderización del "head"):

$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);

Passing language strings to Javascript

There are cases when you may want to output an error message in your JavaScript code and want to use the Joomla mechanism of language strings. You could manage this by using addScriptOptions to pass down each language string you need, but Joomla provides a more succint solution. To pass a language string to JavaScript do in your PHP code, for example,

JText::script('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'); Then in your JavaScript code you can do:

var message = Joomla.JText._('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'); to obtain in the user's language the text message associated with the language constant. Obviously certain language strings have embedded %s characters, so in your JavaScript code you will have to handle that, eg using an external JavaScript sprintf library or string replace, etc.

Insertar secuencias de comandos en línea desde dentro de un archivo PHP

Si Javascript o CSS se generan usando PHP, puedes agregar la secuencia de comandos o la hoja de estilos directamente en la cabeza de tu documento:

$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);

Ejemplo de Javascript

Por ejemplo, el siguiente código se utiliza para definir un texto de ayuda emergente personalizado que toma ventaja de mootools.

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"));

Ten en cuenta que para que este Javascript sea funcionalmente útil, sería necesario incluir el nombre de clase apropiado en el archivo HTML, así como proporcionar el archivo mytooltip.css. Ambos están fuera del alcance de este artículo.

Ejemplos de CSS

Esto también es útil si tu insertas un campo de formulario de CSS en el código. Por ejemplo, en un módulo, puedes ser que desees que un usuario pueda elegir el color del borde. Después de llamar al avlro de los campos de formulario y asignarlo a una variable $bordercolor en mod_example.php. A continuación, en tmpl/default.php se puede incluir lo siguientes:

$document = JFactory::getDocument();
$document->addStyleSheet('mod_example/mod_example.css');
$style = '#example {
	border-color:#' . $bordercolor . ';
	}';
$document->addStyleDeclaration( $style );

Aquí mod_example.css contiene el archivo CSS de cualquier no-parámetro base de estilos. A continuación, el parámetro bordercolor/campo de formulario se agrega por separado.

Agregar Etiqueta Personalizada

Habrá algunas ocasiones en las que incluso estas funciones no son lo suficientemente flexibles, ya que están limitadas a escribir el contenido de las etiquetas <script /> o <style />, y no se puede agregar nada fuera de esas etiquetas. Un ejemplo sería la inclusión de un enlace a hojas de estilos dentro de los comentarios condicionales, que son recogidos únicamente por Internet Explorer 6 y anteriores. Para hacer esto, usa $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 it is declared.

Sample Module Code

Below is the code for a simple Joomla module which you can install and run to demonstrate adding CSS and JavaScript, and can adapt to experiment with the concepts above. If you are unsure about development and installing a Joomla module then following the tutorial at Creating a simple module will help. In a folder mod_css_js_demo create the following 4 files:

mod_css_js_demo.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1" client="site" method="upgrade">
    <name>css js demo</name>
    <version>1.0.1</version>
    <description>Code for including JS and CSS links</description>
    <files>
        <filename module="mod_css_js_demo">mod_css_js_demo.php</filename>
		<filename>demo.css</filename>
		<filename>demo.js</filename>
    </files>
</extension>

mod_css_js_demo.php

<?php
defined('_JEXEC') or die('Restricted Access');

use Joomla\CMS\Factory;

$document = Factory::getDocument();

$options = array("version" => "auto");
$attributes = array("defer" => "defer");
$document->addScript(JURI::root() . "modules/mod_css_js_demo/demo.js", $options, $attributes);
$document->addStyleSheet(JURI::root() . "modules/mod_css_js_demo/demo.css", $options);

$document->addScriptOptions('my_vars', array('id' => "css-js-demo-id2"));

JText::script('JLIB_HTML_EDIT_MENU_ITEM_ID');

echo '<h1 id="css-js-demo-id1">Hello World!</h3>';
echo '<button id="css-js-demo-id2">Click here!</button>';

demo.css

#css-js-demo-id1 {
color: red;
}

demo.js

jQuery(document).ready(function() {
    
	const params = Joomla.getOptions('my_vars');
	console.log(params);
	console.log("JS language constant: " + Joomla.JText._('JLIB_HTML_EDIT_MENU_ITEM_ID'));
	
	var message = Joomla.JText._('JLIB_HTML_EDIT_MENU_ITEM_ID');
	message = message.replace("%s", params.id);
	document.getElementById(params.id).addEventListener("click", function() {alert(message);}); 
});

Zip up the mod_css_js_demo directory to create mod_css_js_demo.zip. Within your Joomla administrator go to Install Extensions and via the Upload Package File tab select this zip file to install this sample mod_css_js_demo module. Make this module visible by editing it (click on it within the Modules page) then:

  1. making its status Published
  2. selecting a position on the page for it to be shown
  3. on the menu assignment tab specify the pages it should appear on

When you visit a site web page then you should see the module in your selected position, and it should display

  • a message Hello World! which the CSS file should change to display in red
  • a button which when you click it will execute an alert() showing the language string and variable which were passed down from the PHP code.

Using your browser's development tools you can also view the <script> and <link> elements within the HTML and see the JavaScript output on the console.