Este método de trabajo con Defer, asíncrono y de carga diferida Dado que se conoce el nombre del archivo de secuencia de comandos, y si será única plantilla de complemento
/* see
* http://stackoverflow.com/questions/984510/what-is-my-script-src-url/984656#984656
* http://www.glennjones.net/Post/809/getAttributehrefbug.htm
*
* iterate all script to find script with right filename
* this work with async and defer (but your script MUST have a unique filemane)
* mozilla support document.currentScript and we use it, if is set
*
* this will not work with local script loaded by jQuery.getScript(),
* since there is no script tag added into the dom. the script is only evaluated in global space.
* http://api.jquery.com/jQuery.getScript/
*
* to fix this odd, you can add a reference in meta (meta[name=srcipt][content=url])
* when you load the script
*/
var scriptFilename = 'jquery.plugins.template.js'; // don't forget to set the filename
var scriptUrl = (function() {
if (document.currentScript) { // support defer & async (mozilla only)
return document.currentScript.src;
} else {
var ls,s;
var getSrc = function (ls, attr) {
var i, l = ls.length, nf, s;
for (i = 0; i < l; i++) {
s = null;
if (ls[i].getAttribute.length !== undefined) {
s = ls[i].getAttribute(attr, 2);
}
if (!s) continue; // tag with no src
nf = s;
nf = nf.split('?')[0].split('/').pop(); // get script filename
if (nf === scriptFilename) {
return s;
}
}
};
ls = document.getElementsByTagName('script');
s = getSrc(ls, 'src');
if (!s) { // search reference of script loaded by jQuery.getScript() in meta[name=srcipt][content=url]
ls = document.getElementsByTagName('meta');
s = getSrc(ls, 'content');
}
if (s) return s;
}
return '';
})();
var scriptPath = scriptUrl.substring(0, scriptUrl.lastIndexOf('/'))+"/";
un jQuery con él: https://github.com/mkdgs/mkdgs-snippet/blob/master/javascript/jquery.plugins.template.js
nota: esto no funcionará con la escritura local cargada por jQuery.getScript(), ya que no hay etiqueta de script añadido en el DOM. el script solo se evalúa en el espacio global. http://api.jquery.com/jQuery.getScript/
para solucionarlo se puede hacer algo como:
function loadScript(url,callback) {
if ($('[src="'+url+'"]').length) return true; // is already loaded
// make a reference of the loaded script
if ($('meta[content="'+url+'"]', $("head")).length) return true; // is already loaded
var meta = document.createElement('meta');
meta.content = url;
meta.name = 'script';
$("head").append(meta);
return $.ajax({
cache: true,
url: u,
dataType: 'script',
async: false,
success : function (script) {
try {
if (typeof callback == 'function') callback();
} catch (error) {
//console.log(error);
}
}
});
}
posible duplicado de [¿Cómo puede obtener el nombre de archivo de secuencia de comandos desde dentro de ese guión?] (Http://stackoverflow.com/questions/710957/how-might-i-get-the -script-filename-from-within-that-script) – Bergi