I am using an import function to import javascript files only when needed. My function looks like the following. They are in the main.js file and inside the jquery ready wrapper.
$(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);
}
});
Let's say we import a javascript file on a mouse click. $import('newfile.js');. However, this newly imported file is unable to access the functions in the main.js javascript file. For example:
// the following function is placed in the newfile.js file
$(function() {
globaltrigger();
});
Any method to make this work?
globaltrigger()really in the global scope, or is it wrapped in window.onload or DOM ready? What error message do you get?ReferenceError: globaltrigger is not definedin firebug. Ah, it seems to be wrapped inwindow.onload. Does $import work with onload?console.log( window.globaltrigger );