Pasar parámetros a archivos JavaScript


A menudo tendré un archivo JavaScript que quiero usar que requiere que ciertas variables se definan en mi página web.

Así que el código es algo así:

<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
   var obj1 = "somevalue";
</script>

Pero lo que quiero hacer es:

<script type="text/javascript" 
     src="file.js?obj1=somevalue&obj2=someothervalue"></script>

Probé diferentes métodos y el mejor hasta ahora es analizar la cadena de consulta de esta manera:

var scriptSrc = document.getElementById("myscript").src.toLowerCase();

Y luego buscar mis valores.

Me pregunto si hay otra manera de hacer esto sin construir una función para analizar mi cadena.

¿Todos saben otros métodos?

Author: Anthony, 2010-02-03

12 answers

Recomiendo no usar variables globales si es posible. Utilice un espacio de nombres y OOP para pasar sus argumentos a través de un objeto.

Este código pertenece al archivo.js:

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // private

    return {
        init : function(Args) {
            _args = Args;
            // some other initialising
        },
        helloWorld : function() {
            alert('Hello World! -' + _args[0]);
        }
    };
}());

Y en su archivo html:

<script type="text/javascript" src="file.js"></script>
<script type="text/javascript">
   MYLIBRARY.init(["somevalue", 1, "controlId"]);
   MYLIBRARY.helloWorld();
</script>
 171
Author: Naeem Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-03 09:33:20

Puede pasar parámetros con atributos arbitrarios. Esto funciona en todos los navegadores recientes.

<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>

Dentro de somefile.js puede obtener los valores de las variables pasadas de esta manera:

........

var this_js_script = $('script[src*=somefile]'); // or better regexp to get the file name..

var my_var_1 = this_js_script.attr('data-my_var_1');   
if (typeof my_var_1 === "undefined" ) {
   var my_var_1 = 'some_default_value';
}
alert(my_var_1); // to view the variable value

var my_var_2 = this_js_script.attr('data-my_var_2');   
if (typeof my_var_2 === "undefined" ) {
   var my_var_2 = 'some_default_value';
}
alert(my_var_2); // to view the variable value

...sucesivamente...

 55
Author: Vlado,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-25 14:28:40

Otra idea que encontré fue asignar un "id" al elemento y pasar los argumentos como atributos data -*. La etiqueta resultante se vería algo como esto:

<script id="helper" data-name="helper" src="helper.js"></script>

El script podría entonces usar el id para ubicarse programáticamente y analizar los argumentos. Dada la etiqueta anterior, el nombre podría ser recuperado así:

var name = document.getElementById("helper").getAttribute("data-name");

Obtenemos name = helper

 32
Author: NewBuddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-16 13:21:47

Echa un vistazo a esta URL. Está funcionando perfectamente para el requisito.

Http://feather.elektrum.org/book/src.html

Muchas Gracias al autor. Para una referencia rápida pegué la lógica principal a continuación:

var scripts = document.getElementsByTagName('script');
var myScript = scripts[ scripts.length - 1 ];

var queryString = myScript.src.replace(/^[^\?]+\??/,'');

var params = parseQuery( queryString );

function parseQuery ( query ) {
  var Params = new Object ();
  if ( ! query ) return Params; // return empty object
  var Pairs = query.split(/[;&]/);
  for ( var i = 0; i < Pairs.length; i++ ) {
    var KeyVal = Pairs[i].split('=');
    if ( ! KeyVal || KeyVal.length != 2 ) continue;
    var key = unescape( KeyVal[0] );
    var val = unescape( KeyVal[1] );
    val = val.replace(/\+/g, ' ');
    Params[key] = val;
  }
  return Params;
}
 17
Author: user378221,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-29 15:22:29

Aquí hay una prueba de concepto muy apresurada.

Estoy seguro de que hay al menos 2 lugares donde puede haber mejoras, y también estoy seguro de que esto no sobreviviría mucho tiempo en la naturaleza. Cualquier comentario para hacerlo más presentable o utilizable es bienvenido.

La clave es establecer un id para el elemento script. El único problema es que esto significa que solo puede llamar al script una vez, ya que busca ese ID para extraer la cadena de consulta. Esto podría arreglarse si, en cambio, el script recorre todos consulta elementos para ver si alguno de ellos apunta a él, y si es así, utiliza la última instancia de dicho elemento de script. De todos modos, con el código:

Se llama al script:

window.onload = function() {
//Notice that both possible parameters are pre-defined.
//Which is probably not required if using proper object notation
//in query string, or if variable-variables are possible in js.
var header;
var text;

//script gets the src attribute based on ID of page's script element:
var requestURL = document.getElementById("myScript").getAttribute("src");

//next use substring() to get querystring part of src
var queryString = requestURL.substring(requestURL.indexOf("?") + 1, requestURL.length);

//Next split the querystring into array
var params = queryString.split("&");

//Next loop through params
for(var i = 0; i < params.length; i++){
 var name  = params[i].substring(0,params[i].indexOf("="));
 var value = params[i].substring(params[i].indexOf("=") + 1, params[i].length);

    //Test if value is a number. If not, wrap value with quotes:
    if(isNaN(parseInt(value))) {
  params[i] = params[i].replace(value, "'" + value + "'");
 }

    // Finally, use eval to set values of pre-defined variables:
 eval(params[i]);
}

//Output to test that it worked:
document.getElementById("docTitle").innerHTML = header;
document.getElementById("docText").innerHTML = text;
};

Script llamado a través de la siguiente página:

<script id="myScript" type="text/javascript" 
        src="test.js?header=Test Page&text=This Works"></script>

<h1 id="docTitle"></h1>
<p id="docText"></p>
 12
Author: Anthony,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-03 11:15:59

Se utilizan variables globales: - D.

Así:

<script type="text/javascript">
   var obj1 = "somevalue";
   var obj2 = "someothervalue";
</script>
<script type="text/javascript" src="file.js"></script">

El código JavaScript en 'file.js' puede acceder a obj1 y obj2 sin problema.

EDIT Solo quiero añadir que si 'archivo.js quiere comprobar si obj1 y obj2 se han declarado.Puede utilizar la siguiente función.

function IsDefined($Name) {
    return (window[$Name] != undefined);
}

Espero que esto ayude.

 10
Author: NawaMan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-03 09:19:10

Podría ser muy simple

Por ejemplo

<script src="js/myscript.js?id=123"></script>
<script>
    var queryString = $("script[src*='js/myscript.js']").attr('src').split('?')[1];
</script>

Luego puede convertir la cadena de consulta en json como se muestra a continuación

var json = $.parseJSON('{"' 
            + queryString.replace(/&/g, '","').replace(/=/g, '":"') 
            + '"}');

Y luego puede usar como

console.log(json.id);
 9
Author: Tofeeq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-01 11:27:48

Esto se puede hacer fácilmente si está utilizando algún framework Javascript como jQuery. Así,

var x = $('script:first').attr('src'); //Fetch the source in the first script tag
var params = x.split('?')[1]; //Get the params

Ahora puede usar estos parámetros dividiendo como sus parámetros variables.

El mismo proceso se puede hacer sin ningún marco, pero tomará algunas líneas más de código.

 6
Author: GeekTantra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-03 09:20:05

Bueno, podría tener el archivo javascript siendo construido por cualquiera de los lenguajes de scripting, inyectando sus variables en el archivo en cada solicitud. Tendría que decirle a su servidor web que no reparta archivos js estáticamente (usar mod_rewrite sería suficiente).

Tenga en cuenta, sin embargo, que pierde cualquier almacenamiento en caché de estos archivos js, ya que se alteran constantemente.

Adiós.

 1
Author: aefxx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-03 09:21:51

Buena pregunta y respuestas creativas, pero mi sugerencia es hacer que sus métodos paramterizados y que debe resolver todos sus problemas sin ningún truco.

Si tienes función:

function A()
{
    var val = external_value_from_query_string_or_global_param;
}

Puede cambiar esto a:

function B(function_param)
{
    var val = function_param;
}

Creo que este es el enfoque más natural, no necesita crear documentación adicional sobre 'parámetros de archivo' y recibe lo mismo. Esto es especialmente útil si permite que otros desarrolladores usen su archivo js.

 1
Author: dzida,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-28 16:53:50

No, realmente no puede hacer esto agregando variables a la porción querystring de la URL del archivo JS. Si está escribiendo la porción de código para analizar la cadena que le molesta, tal vez otra forma sería codificar json sus variables y ponerlas en algo como el atributo rel de la etiqueta? No se cuan válido es esto en términos de validación HTML, si eso es algo que te preocupa mucho. Entonces solo necesita encontrar el atributo rel del script y luego json_decode eso.

Eg

<script type='text/javascript' src='file.js' rel='{"myvar":"somevalue","anothervar":"anothervalue"}'></script>
 0
Author: Dal Hundal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-03 09:25:11

No es html válido (no lo creo) pero parece que funciona si creas un atributo personalizado para la etiqueta de script en tu página web :

<script id="myScript" myCustomAttribute="some value" ....>

Luego acceda al atributo personalizado en javascript:

var myVar = document.getElementById( "myScript" ).getAttribute( "myCustomAttribute" );

No estoy seguro de si esto es mejor o peor que analizar la cadena de origen del script.

 0
Author: Cor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-14 04:53:24