pewpewlasers
pewpewlasers

Reputation: 3215

Import javascript files when needed and global variables

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?

Upvotes: 1

Views: 1286

Answers (2)

MrCode
MrCode

Reputation: 64526

Your problem is as I suspected, the globaltrigger() function is not in the global scope. It's inside the jQuery DOM ready function, so is not accessible from outside.

Move it into the global scope:

function globaltrigger(){
    alert('');
}

$(function(){
    // dom ready stuff
});

It's good practice to avoid polluting the global space with lots of variables and functions. You can store your functions/variables under an object which is a simple way of achieving namespaces.

var SomeApp = {};

SomeApp.globaltrigger = function(){
    alert('');
};

In the external JavaScript you can call it:

SomeApp.globaltrigger();

This is good because all of your code lives under the SomeApp object.

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59232

The DOM ready creates a closure, making your function limited to only that scope. You can declare your function to be global like this:

window.globaltrigger = function(){
    alert('');
}

Now the function is truly global and can be called by other scripts.

Upvotes: 1

Related Questions