我正在使用導入功能僅在需要時才導入javascript文件。我的功能如下所示。它們位於main.js
文件中,並位於jquery ready包裝器中。當需要和全局變量時導入javascript文件
$(function() {
function globaltrigger(){
alert('');
}
function $import(src){
var scriptElem = document.createElement('script');
scriptElem.setAttribute('src',src);
scriptElem.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptElem);
}
});
比方說,我們導入一個JavaScript文件的鼠標點擊。 $import('newfile.js');
。但是,這個新導入的文件無法訪問main.js
JavaScript文件中的功能。例如:
// the following function is placed in the newfile.js file
$(function() {
globaltrigger();
});
任何方法使這項工作?
這應該工作。 'globaltrigger()'真的在全局範圍內,還是被包裝在window.onload或DOM ready中?你會得到什麼錯誤信息? – MrCode
腳本完全加載後是否調用該函數?當你點擊加載是異步的,所以它可能是文件未被完全加載的情況,並且你正在調用函數 –
@MrCode'ReferenceError:globaltrigger未定義'在螢火蟲中。啊,它似乎被包裹在'window.onload'中。 $ import是否與onload一起工作? – pewpewlasers