In my project, I have designed a JavaScript page to render HTML data but I'm getting the above error. My code is:
global.getElementById('divPartnerGrid').innerHTML = "<table width='100%'><tr><td align='middle' style='vertical-align:middle; position:centre;'><img src='../Content/images/ajax-loader(2).gif'/></td></tr><tr><td align='middle' style='vertical-align:middle; position:centre;'>"+loadingLabel+"...</td></tr></table>"
While running the project,it will break at this line. Can anyone please let me know, what caused this error to come?
I donĀ“t know what global is either but the getElementById method is defined on the document so you probably simply want
document.getElementById('divPartnerGrid').innerHTML = "...";
replace global with document, even if global is a variable you created that points to window (or this in the global scope), you still need a document in which you want to search for elements.
Also, make sure the page is loaded before this script runs: you can't get an element if it's not loaded yet
You have probably copied the global thing from an example that has encapsulated the global variable while you haven't done the same.
This is done in the following example where the document (which is probably what you want to use as others have pointed out) where document is sent in to the self envoking function so that global inside that scope would actually refer to document.
;(function(global) {
global.getElementById(/* */);
})(document);
This is typical for libraries that could be used on the server where the global value may be different from the one in a browser.
Related
Have you ever taken a look under the hood at the jQuery 1.4 source code and noticed how it's encapsulated in the following way:
(function( window, undefined ) {
//All the JQuery code here
...
})(window);
I've read an article on JavaScript Namespacing and another one called "An Important Pair of Parens," so I know some about what's going on here.
But I've never seen this particular syntax before. What is that undefined doing there? And why does window need to be passed and then appear at the end again?
The undefined is a normal variable and can be changed simply with undefined = "new value";. So jQuery creates a local "undefined" variable that is REALLY undefined.
The window variable is made local for performance reasons. Because when JavaScript looks up a variable, it first goes through the local variables until it finds the variable name. When it's not found, JavaScript goes through the next scope etc. until it filters through the global variables. So if the window variable is made local, JavaScript can look it up quicker.
Further information: Speed Up Your JavaScript - Nicholas C. Zakas
Undefined
By declaring undefined as an argument but never passing a value to it ensures that it is always undefined, as it is simply a variable in the global scope that can be overwritten. This makes a === undefined a safe alternative to typeof a == 'undefined', which saves a few characters. It also makes the code more minifier-friendly, as undefined can be shortened to u for example, saving a few more characters.
Window
Passing window as an argument keeps a copy in the local scope, which affects performance: http://jsperf.com/short-scope. All accesses to window will now have to travel one level less up the scope chain. As with undefined, a local copy again allows for more aggressive minification.
Sidenote:
Though this may not have been the intention of the jQuery developers, passing in window allows the library to be more easily integrated in server-side Javascript environments, for example node.js - where there is no global window object. In such a situation, only one line needs to be changed to replace the window object with another one. In the case of jQuery, a mock window object can be created and passed in for the purpose of HTML scraping (a library such as jsdom can do this).
Others have explained undefined. undefined is like a global variable that can be redefined to any value. This technique is to prevent all undefined checks from breaking if someone wrote say, undefined = 10 somewhere. An argument that is never passed is guaranteed to be real undefined irrespective of the value of the variable undefined.
The reason to pass window can be illustrated with the following example.
(function() {
console.log(window);
...
...
...
var window = 10;
})();
What does the console log? The value of window object right? Wrong! 10? Wrong! It logs undefined. Javascript interpreter (or JIT compiler) rewrites it this way -
(function() {
var window; //and every other var in this function
console.log(window);
...
...
...
window = 10;
})();
However, if you get the window variable as an argument, there is no var and hence no surprises.
I don't know if jQuery is doing it, but if you are redefining window local variable anywhere in your function for whatever reason, it is a good idea to borrow it from global scope.
window is passed in like that just in case someone decides to redefine the window object in IE, I assume the same for undefined, in case it's re-assigned in some way later.
The top window in that script is just naming the argument "window", an argument that's more local that the global window reference and it what the code inside this closure will use. The window at the end is actually specifying what to pass for the first argument, in this case the current meaning of window...the hope is you haven't screwed up window before that happens.
This may be easier to think of by showing the most typical case used in jQuery, plugin .noConflict() handling, so for the majority of code you can still use $, even if it means something other than jQuery outside this scope:
(function($) {
//inside here, $ == jQuery, it was passed as the first argument
})(jQuery);
Tested with 1000000 iterations. This kind of localization had no effect in performance. Not even a single millisecond in 1000000 iterations. This is simply useless.
I create a new global object and then put everything in to that new object so it doesn't interfere with anything else anyone else does. After calling the document.ready() function this gets moved to window.bf for unknown reasons. I've reduced this down to a simple example. Anyone have any ideas on what is happening?
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
debugger;
var bf = {}; // Namespace
bf.vars = [];
bf.vars['onclick'] = "";
$(document).ready(function() {
bf.noop = function() {}
bf.noop();
window.bf.noop();
});
</script>
</head>
<body>Test</body>
</html>
So I wind up with two "bf"s. One is the original global object and the second one is the window.bf object. My problem is: Originally, the global object had all of the functions and variables in it. Now the global variable has nothing except bf.vars (an array). Everything else is now in the window.bf object (including everything that was supposed to go in to the global bf.vars array yet I never asked for that to happen.
Up until last Friday (9/25/2015) this did not happen. Now it does.
Update: I just tried removing the document.ready() function. If you remove the document.ready() part - then the global bf object goes back to being a global variable. So this appears to have something to do with jQuery itself.
Before anyone asks: The reason the document.ready() is being used is because some of the functions I define make reference to locations that need to be loaded and jQuery says to use the document.ready() function in order to ensure all elements have been loaded before execution starts. The bf.noop() function is just to give an example of a function and to show that the function no longer shows up in the global bf object.
Screen capture with document.ready():
Screen capture without document.ready():
Better?
In the top-level scope of a script tag, all variables get implicitly attached to window.
The good news is, you actually don't have two bf objects, you only have one with two ways to access it.
var bf = {};
bf.foo = "bar";
document.getElementById('output').innerHTML = JSON.stringify(window.bf, undefined, 4);
<div id="output"></div>
A variable declared outside the scope of a function is bound to the global scope. Since you're declaring var bf = {} inside the script tag, its parent is the window object.
This MDN document is a good read on variables in JavaScript.
Rossipedia has both two good answers as well as leading me to find the problem. See his posts.
For unknown reasons, jQuery version 1.11.1 (I'm using v1.11.3 and thus the 1.11.1|3 in my post) has some kind of an error that was fixed in jQuery version 2.1.3.
But I also found that one of the programs I use to generate the menu for our site was generating an old function name (showIt instead of show_menu) which was causing problems also. By fixing the generated function name the problem has gone away.
This does NOT mean that the jQuery folks can go "Yeah! We don't have to fix anything!" because this is a valid error and the simple code I posted shows how to break jQuery which might mean there is some way to cause real problems with jQuery. So basically, this should be looked at by someone more in tune with jQuery to find out why the code I posted does what it does. Then they can come back and say "You idiot! You did BLAH! and you shouldn't have!" or maybe "Thanks for locating this really obscure problem that no one else in the entire world has come across or cares about." In any event - this is now a known problem. :-)
If I have the following JavaScript code:
<script id="someJS">
var boom = 'boom';
function example(){
alert(boom);
}
</script>
and then do:
$('#someJS').remove();
I can still call example() even though that JavaScript function is no longer inside the DOM... How can I remove it?
I don't want to null the actual function(s) and variables with: boom = null; example = null; as I don't always know what is inside the JavaScript file. For example the function names, variables, etc. I need to be able to remove the entirity of what was inside that script tag.
Update: For those that wanted to know the user case for this:
Basically in an app I am working on, we have custom JavaScript added for certain clients that when a button is clicked e.g. save, then checks if certain functions exist and then runs them. However because this save button is generic it means that that the custom code gets called all the time after it's added even if it's no longer relevant.
The solution we have come up with (someone had posted this as an answer but they removed it for some reason) was to namespace it all like:
DynamicJS = {
boom: 'boom',
example: function(message) {
alert(message);
}
}
And then we can just do: delete DyanmicJS;
Which removes all the functions and variables inside this namespace from the global scope, effectively binning off what the script file added.
Although I am sure this is not a perfect solution as if you had event listeners inside the file, I'm sure they would still exist!
How can I remove it? I don't want to null the actual function, as I don't always know what is inside the JS file.
You can't. Script code is executed, creates things in the JavaScript environment, and is completely disconnected from the script element that loaded it. Other than completely reloading that environment, if you don't know what the code did, you can't undo it.
Even if you could infer some of what the code did (for instance, by making a list of globals before and after), while you could remove new globals you detected (or at least set them to null or undefined, since delete doesn't work wiith globals added via function declarations or var), that doesn't tell you what event handlers, web workers, etc. the code may have hooked up.
$('#someJS').remove(); only removes the script element from the page.
By the time the element is removed, the script has already been interpreted, which means example has been added to the global scope.
To properly remove that function you could do this:
window.example = null;
However, apparently you don't want to do this, and this will result in a load of errors if there's script elsewhere that actually uses example.
An alternative could be to assign an empty function to it:
window.example = function(){};
This will prevent the "removal" from resulting in errors.
(Aside from the function not returning values when that may be expected)
Once the function has been processed, it is now part of the window's executable list of functions - regardless of if you remove the original source or not.
To remove the function entirely, try:
window['example'] = null;
However, based on your last comment:
I don't want to null the actual function, as I don't always know what is inside the JS file.
It sounds like you want to maintain reference to the function but not have it executable directly? If that's the case, you can store a reference to it and remove the original:
var _exampleBackup = window['example'];
window['example'] = null;
To call it, you can now use:
_exampleBackup();
And to restore it, if you need to:
window['example'] = _exampleBackup;
example();
That function is still in the window.
Code that you put inside a script tag will be ran when the element is created and has no value (roughly) by itself anymore. Removing the tag will not affect the document and the impact it had on it (generally).
To remove the function you need to remove the example property on the window object, which is how the function will be defined, running the code above.
$('#someJS').remove();does nothing more than removing the text from the DOM, but does nothing to the actual function (nor the file), since it is parsed and executed.
In order to delete the function, you could either set it to null or simply overwrite it with example=function(){};
JavaScript Hoisting
There is a concept in JavaScript called Hoisting. In this phase, compiler parse all JavaScript code and declares variables and function at the beginning of scope. In your case, function example and variable boom is already declared and kept in memory. When you run that method, interpreter will call that method and interpret it instead of interpreting actual JavaScript code. You are deleting script block after it went in memory. And thats why it is still executable.
Approaches to do this
1) Use object oriented approach. Add your method in a object, and when you want to delete it, delete that property by using delete.
2) Create one variable which holds a function which contains your code to execute, and set that variable undefined when you want.
I have a declared variable and jQuery code telling a button to store a form's value as the value of that variable and execute a function.
var verb = "";
$( "#submit" ).click(function() {
verb = $('#enter').val();
teConjugate();
});
In the teConjugate() function, I have placed a lot of functions and variables using the "verb" variable that I want to use outside the teConjugate() function. However, when I declare these functions and variables globally, they use the globally declared "verb" (which is an empty string). I've done research and I know that it has something to do with the rendering of the page (as console.log does not raise the same issues).
The only thing I've thought of is putting said functions and variables in to a initialize function which executes on button click, to reduce the hassle of copy pasting everything. However, this did not work either.
Is there any solution? Any help would be appreciated.
JSbin with the dilemma.
As one can see, there are a lot of variables and functions that would be more useful outside the function.
There is nothing wrong with what you have shown here (see this fiddle). I suspect it is something to do with your teConjugate(); function.
Many thanks in advance. I'm working out of a schoolbook and they're using one function to call another which opens a window:
function rtest(){
content='dans window';
oneWindow=open("","Window 1","width=450,height=290");
newWindow(oneWindow);
}
function newWindow(x){
x.document.close();
x.document.open();
x.document.write(content);
x.document.close();
x.moveTo(20,20);
x.focus();
}
So everything works fine, but my question is this: how is the newWindow() function able to access the contents of the "contents" variable in the rtest() function? And why, if I preface the "content" variable with "var", like this:
function rtest(){
**var content='dans window';**
oneWindow=open("","OneWindow","width=450,height=290");
newWindow(oneWindow);
}
...does an error get thrown (and the contents of the new window left blank)?
Can anybody explain to me what the difference between using var and not using var is?
Thank you!
Daniel
if you dont use var inside the rtest, it is automatically a global variable. which is why it is accessible from other javascript codes including newWindow. now, when you use var, it automatically a variable inside the rtest scope, so the ones that can use it now are those inside the same scope.
If you declare the variable using var inside the original function, it will become a local variable and will not be visible outside the function.
If you don't declare the variable at all, it will be global. However, best practice is to declare global variables. If your textbook doesn't do this, consider replacing it. If your professor doesn't do this, consider replacing (or reforming) him. :-) If you have trouble convincing him, you can (but not necessarily should) mention that I'm one of the top 200 users here.
For example:
var content;
function rtest(){
content='dans window';
oneWindow=open("","Window 1","width=450,height=290");
newWindow(oneWindow);
}
Also, the best way to open a blank window is to call open("about:blank", ...), not open("", ...).
It's about the function-scope, if you declare your variable with var, it will be available only in the scope of the function where you did it.
If you don't use the var statement, and you make an assignment to an undeclared identifier (an undeclared assignment), the variable will be added as a property of the Global object.
If you don't use var, then you are creating a global variable; that is, a variable that is accessible from any code anywhere in your program. If you use var, you are creating a local variable, which is a variable that is only accessible from within the scope in which it is defined (generally, the function it is defined in).
While global variables can be convenient at first, it's generally a bad idea to use them. The problem is that all of your code will share that one global variable; in the future, if you need to have two or more different versions of that variable for whatever reason, you won't be able to separate the two uses. Global variables can also be accessed or changed from anywhere within your program, so it can be hard to figure out what might be modifying or depending on one, while local variables can only be accessed within a limited, well defined section in code, which can easily be inspected.
With var you declare a local variable in the function which is thus not visible outside this function. Without var you are actually working on the window object and set or overwrite a field of it. Your global scope in client side Javascript is always the window object. So you could also have written window.content='dans window'; to make clearer what you are actually doing there, but otherwise it would be identical. By the way: the window variable is itself just a field of the window object that refers recursively back to the window.