में स्थगित करें, async और आलसी लोड हो रहा है साथ इस पद्धति का काम काम करता है के बाद से आप अपनी स्क्रिप्ट के फ़ाइल नाम पता है, और अगर यह हो जाएगा इसके साथ अद्वितीय
/* 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('/'))+"/";
एक jQuery प्लगइन टेम्पलेट: https://github.com/mkdgs/mkdgs-snippet/blob/master/javascript/jquery.plugins.template.js
ध्यान दें: इस,) jQuery.getScript (द्वारा लोड स्थानीय स्क्रिप्ट के साथ काम नहीं करेगा क्योंकि वहाँ कोई स्क्रिप्ट नहीं टैग डोम में जोड़ा है। स्क्रिप्ट का मूल्यांकन केवल वैश्विक अंतरिक्ष में किया जाता है। http://api.jquery.com/jQuery.getScript/
इसे ठीक करने के लिए आप की तरह कुछ कर सकते हैं:
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);
}
}
});
}
संभव डुप्लिकेट [कैसे मुझे लगता है कि स्क्रिप्ट के भीतर से स्क्रिप्ट फ़ाइल नाम मिल सकता है?] (Http://stackoverflow.com/questions/710957/how-might-i-get-the -स्क्रिप्ट-फ़ाइल नाम-से-भीतर-उस-स्क्रिप्ट) – Bergi