I have a situation where I'm trying to consolidate several Javascript files into one, and conditionally apply them. I don't want to modify the actual files. Is there a way I can wrap these files and call them on demand?
The catch is, some of these files have function xyz() {} in them. So, wrapping them with if (false) { function xyz() {} } makes bad things happen.
For example, if this is my code...
if (includeFile) {
/* The file */
function foo() {}
/* The file */
}
The problem becomes that Chrome will see foo() and place it in the global scope even if includeFile is false.
The easy solution would be to modify it to be var foo = function() {} but I can't modify these files.
I also have a general concern about running eval() on these functions since they are fairly huge. (Think jQuery wrapped in a function. If this isn't a problem then maybe eval is the answer?)
I was hoping I could nest functions and pass window in as the scope, but tried it on jsFiddle and it didn't seem to work.
(function() {
function foo() {
alert('it works');
}
}).apply(window, []);
foo();
There are a few similar questions. But, none addressed the same situation that I have. Thanks.
Have you considered using a library like require.js? There are several libraries out there that can do this for you in a more elegant fashion.
If you don't want a dependency-loading library, but you're using jQuery or some similar library, you can load scripts conditionally using an AJAX request (in jQuery, you'd use the script dataType). This is far better than a simple eval(), but less robust when you're trying to manage a series of dependencies.
Another option here, if you want to simply concatenate everything, is to wrap each file in an anonymous function and then assign the necessary elements to the window object, placing them in the global scope:
(function(window) {
/* file 1 here */
function xyz() {
// etc ...
}
/* end file 1 */
// now selectively choose what you want to be
// in the global scope
window.xyz = xyz;
}(window));
xyz();
This requires more work for you, however, to identify what you want to be available globally. Note that it's note necessary to pass window in as an argument to the anonymous function, but it's not a bad idea if you're going to be be referring to it multiple times (this speeds up references and allows for variable-name munging during code compression).
Related
I am creating a wrapper for some arbitrary code (let's call it managed code). The managed code may include some functions that are defined in the window scope and are expected by other scripts on the page (horrible, 1997, practices, I know, but such is what I have to deal with), as global functions.
The purpose of the wrapper is to delay executing the wrapped code until jQuery is loaded. It looks like this:
(function () {
var once = true,
check = setInterval(function () {
if (window.$ && once) {
once = false; // setInterval can stack up if the UI freezes. Ensure this only gets called once.
executeBundle();
clearInterval(check);
console.log('Jquery loaded');
}
}, 100);
})()
// Wrapper proper
function executeBundle() {
// oodles of code of any origin
}
Now that the managed code is wrapped inside the executeBundle function, all functions/variables declared within it will be scoped to that function. This isn't a problem for the managed code itself, but for other scripts that load separately that may rely on global functions it provides.
I'd like to know if anyone knows a strategy like eval, but without the security issues, that may allow me to preserve the window scope for the running of the managed code. The constraint is that I can't modify the managed code at all--just the wrapper.
Based on T.J. Crowder's phenomenal answer, I realized that I could add the managed code to a <script> element and add that to the <head> like this:
var codeBundle = // Code in one long string
function evaluateBundle() {
var script = $('<script type="text/javascript"/>')
script.html(codeBundle);
$('head').append(script);
}
And let the parser evaluate the code.
I'd like to know if anyone knows a strategy like eval, but without the security issues
If you're evaling code of your own that you would run by having it in a script tag anyway, there are no security issues. You're running code either way.
You can't do this if the code you're wrapping will appear directly within evaluateBundle and it has declarations (vars and function declarations) that were supposed to be at global scope. Handling those would require modifying the wrapped code.
You can do this if you load that code separately, though, and then do a global eval on it. For instance, put it in a script block with a non-JavaScript type so the browser doesn't execute it:
<script type="x-code-to-wrap"></script>
...and then:
function evaluateBundle() {
var code = document.querySelector('script[type="x-code-to-wrap"]').textContent;
(0, eval)(code);
}
(The (0, eval)(code) bit is the global eval, more on MDN).
You may have to adjust the textContent part of that for cross-browser compatibility. This question's answers suggest using jQuery's html function:
function evaluateBundle() {
(0, eval)($('script[type="x-code-to-wrap"]').html());
}
Live example on JSBin
My colleague has been extensively using IIFE inside (document).ready in his code. Now, I've read this post:
JQuery best practise, using $(document).ready inside an IIFE?
This got me thinking if we should use $(document).ready inside IIFE or is it also fine the other way around as my colleague is doing.
So basically, his code is setup like this:
jQuery(function() {
(function($) {
//...
// Code here
//...
})(jQuery);
});
Is what he is doing generally fine?
Some may argue that this is a matter of style/opinion, but if you consider the typical goal of an IIFE in that context I believe the answer is yes, it is acceptable to use your alternative way, but there is a potential drawback.
Wikipedia has to say that:
Immediately-invoked function expressions can be used to avoid variable hoisting from within blocks, protect against polluting the global environment and simultaneously allow public access to methods while retaining privacy for variables defined within the function.
Neither method pollutes the global namespace, because they don't declare any variables. Therefore, it should be fine to use either way. Although note that it is partially redundant because the function handler for the ready event already creates a new scope, and also note it is the most common practice to see IIFE functions encapsulate all of the code in a file.
One drawback to the way that your colleague is using: If you did want to do some javascript logic that didn't depend on the DOM being ready, then you would not have the benefits of the IIFE if you put your code outside of the IIFE. So something such as this would not be safe:
// Non-DOM-ready-required code here (NOT scope-safe)
jQuery(function() {
(function($) {
//...
// DOM-ready-required code here
//...
})(jQuery);
});
Using the common style gives you the full IIFE benefit:
(function($) {
// Non-DOM-ready-required code here (scope-safe)
$(function() {
//...
// DOM-ready-required code here
//...
});
})(jQuery);
In my opinion, your colleague is jumping through an extra hoop for no reason. I'm going to ignore the outer $(document).ready as it's of no real consequence.
/*jQuery(*/function() {
(function($) {
//...
// Code here
//...
})(jQuery);
}/*);*/
Using an IIFE as the entire body of the callback to jQuery confers no extra benefit in scope isolation. It's the same as if the code were
/*jQuery(*/function() {
//...
// Code here
//...
});
The only thing that the IIFE has done is allow you to reference jQuery as $.
Now, if there were more substantive code inside the callback, then there could be some benefit in using an inner IIFE. In the following example, the callback contains two IIFEs,
jQuery(function() {
// IIFE
(function($) {
//...
// Code here
//...
})(jQuery);
// IIFE 2
(function($) {
//...
// Code here
//...
})(jQuery);
});
and the use of IIFE's allows scope isolation between the two blocks of code.
Back to the main question:
This got me thinking if we should use $(document).ready inside IIFE or
is it also fine the other way around as my colleague is doing.
Now, to be honest, I don't understand why either of these should be regarded as a best practice, even after looking at your link. The people who answered never explained why it should be a best practice.
Looking at
(function($) {
$(document).ready(function() {
// other code here
});
})(jQuery);
versus
//(function($) {
$(document).ready(function() {
// other code here
});
//})(jQuery);
There really isn't any significant advantage. Just as in my earlier example, the use of the IIFE offers no scope isolation advantage, and does nothing other than to allow you to reference jQuery via $.
However, in the actual linked question , the code looks like this:
(function($) {
// other code here 1
$(document).ready(function() {
// other code here 2
});
})(jQuery);
and in this case, the IIFE does serve a purpose of keeping the variables used in other code here 1 from leaking out to global scope. But this has nothing at all to do with $(document).ready(). Restructuring the code as
(function($) {
// other code here 1
})(jQuery);
jQuery(document).ready(function() {
// other code here 2
});
does the same thing.
The moral of this answer is that using an IIFE to wrap loose code that's not already inside a function gives you benefits, while wrapping code that's already inside a function doesn't give you anything (unless you count changing the reference).
I have this big "class".
function MyFunc(){
this.prop = true;
}
MyFunc.prototype.method1 = function(){
// code here
}
etc, lots of methods in one file. and then, the instance is created and run on document.ready
And then, I have one particularly large method, that I would like to move to a separate file. However, when I move it and include them one after another, main file first, the second one says MyFunc is not defined. I cannot add that prototype.method declaration on document.ready, also, since it has to be ready before instance is initialized.
What pattern should I use here to properly organize my code? Thanks.
Long story short, I have a long code that uses jQuery. Lots of files, functions, etc. A less than ideal amount of our users are having issues with our code because some addons, toolbars and the like they have installed breaks our JavaScript code because of jQuery gets included twice and nasty stuff like that.
I thought I could just
Include jQuery
Use $.noConflict
Then include the whole rest of my code between something like:
.
(function($) {
// All of my code goes here.
})(jQuery);
I haven't checked if this fixes our issues with those users, but it does work. The problem is, in one part of the site (image upload) we have an iframe that needs to call some of those functions defined in our big chunk of code. I've tried putting those functions out of this unnamed function call, but it uses, on itself, other functions which have to be there.
Any idea or workaround of how could I be able to access functions defined inside that function (shown above) from a code that's outside of it?
Thanks!
You cannot access a function context from the "outside world". Well, to be accorate you could do it in some older js engines which allowed for accessing .__parent__ attributes, but that is old'n'busted and no longer available.
However, you would need to either expose some functions within your closure, or you creating a namespace object where you write all of your logic in (which also has to be available in the parent context).
So I'd suggest something like
(function( $ ) {
function myFunc() {
// do stuff
}
function anotherFunc() {
}
window.myFunc = myFunc; // expose myFunc globally
}( jQuery ));
Maybe even better:
var myNameSpace = { };
(function( $ ) {
myNameSpace.myFunc = function() {
// do stuff
};
}( jQuery ));
// somewhere else
myNameSpace.myFunc();
It is not an ideal practice, but you can declare those functions in the global scope.
(function($) {
globalFunct = function (arg1, arg2) { // Don't use var keyword
...
};
})(jQuery);
It isn't ideal because you can run into naming collisions, much like you are observing with jQuery. Improve upon this approach by putting all of your globally-accessible methods in a "package." Choose a unique name for it. This will prevent collisions.
// Somewhere outside of your anonymous function, in the global scope
var myPackage = {};
(function($) {
myPackage.globalFunct = function (arg1, arg2) {
...
};
})(jQuery);
Then call that method by invoking myPackage.globalFunct().
Why are you wrapping your code in a call to the jQuery function object which you pass in to your self-executing anonymous function; are you meaning to create a jQuery object from all of your code?
In order to expose your code to the outside world, you need to assign your functions and objects to an object which is outside of the scope of your code, such as the window object.
For example, if you had created an object containing various methods and properties that you wanted to expose, you could do this:
//Your self-executing anonymous function
(function($)
{
//Object which contains various useful methods and properties
var useful = {...};
//Expose it to the outside world
window.Useful = useful;
})(jQuery);
EDIT: as others have noted, it is not an ideal solution as you will indeed run into naming collisions if you are not careful. Also, using an object external to your anonymous function as a namespacing object (as others have stated) is my preferred method
Yes, you can "export" the function from within a closure:
Yes, you can "export" the function from within a closure:
(function() {
function a() {
console.log("a");
}
function b() {
a();
console.log("b");
}
// make b globally available
window.b = b;
})();
b();
window.PARTY_CATS_jQuery = jQuery.noConflict(true);
(function($) {
$(function() {
// All of my code goes here.
});
})(COMPANY_NAME_jQuery);
Then just use PARTY_CATS_jQuery in your global functions
If you feel PARTY_CATS_ is not a unique enough name pick something safer like BABY_KILLER_jQuery
Just wanted to know if it was a good JavaScript practice.
Let's say I have many Web pages that all call an initialization function "init()", would it be the right thing to use an IIFE inside my pattern to run the function everytime the script is loaded?
var foo = (function() {
var bar = "something";
(function init() {
// Do something crazy that's gonna be the same across all my web pages
// like adding an event listener or something
// ...
document.write('page init...');
}());
function privatePage1() {
// This stuff is gonna be used only in page1.html via foo.privatePage1
document.write('page 1' + bar);
}
function privatePage2() {
// This stuff is gonna be used only in page2.html via foo.privatePage2
document.write('page 2' + bar);
}
return {
privatePage1: privatePage1,
privatePage2: privatePage2
}
}());
This is a pretty subjective area, but here's my take:
When you use the module pattern, you're providing a contained set of functionality to the rest of your code. It's essentially a mini-library.
In general, I wouldn't expect a library to do anything when I load it, other than initialization steps that are entirely internal to the library (e.g. setting up the configuration, instantiating a few necessary objects, etc) - nothing that actually affects the DOM or otherwise significantly alters the environment (which is why I've never been entirely comfortable with libraries like Date.js or Prototype that change the prototypes of basic objects).
There are a couple of reasons for this, but the main one is that I don't want to have to worry about the load order of my libraries/modules, other than simply managing dependencies. Independent modules shouldn't affect each other at all. When you manipulate the DOM in your module at load time, sooner or later you'll realize that another piece of your code is expecting the DOM to be in a certain state at a certain time, and that you now have to care about whether you load your module before or after that time. This is an extra bit of complexity that's essentially hidden in the script tag that loads your module.
The other issue here is portability and adaptability. Maybe you'll want to use your module in another project with another DOM setup. Maybe you'll want to pass a different DOM element or config variable to the init() function on a specific page. If you execute init() automagically, you lose the opportunity for configuration.
So what I generally do is to set the init() method as an attribute of the returned module object:
var foo = (function() {
function init() {
// Do something crazy that's gonna be the same across all my web pages
}
//...
return {
init: init,
// etc
}
}());
and then call it as needed elsewhere in my code:
foo.init();
Yes, this adds an extra line of redundant code to the initialization for all my pages (though this is probably just one other script anyway, so the added weight is all of 11 characters). But it allows me a more fine-grained control over when the module is initialized, and offers a hook for configuration arguments when I (inevitably) determine I need them later.
Is the init() function the same across web pages? If so, this is what I'd do:
var foo = (function()
{
init();
return {};
}());
If not, I don't see a reason to use an IIFE, and would simplify your original code like so:
var foo = (function()
{
/* body of the original IIFE here */
return {};
}());