I have this js piece which I use for django channels:
var chatSocketSender1 = new WebSocket(
'ws://' + window.location.host + '/ws/my_socket1/'
)
function send() {
var msg = "some message"
var receiver_id = 111
window['chatSocketSender1'].send( JSON.stringify({
'msg': msg,
'receiver_id': receiver_id
}) )
}
document.querySelector('#send_button').onclick = function() {
send();
}
The problem is that this js code only works if I put that after latest element of HTML:
<head>
...
</head>
<body>
// whole html content here
<script>
// js piece here
</script>
</body>
But if I use jquery's on load method like:
<head>
<script>
$(window).on('load', function () {
// js piece here
});
</script>
</head>
<body>
// whole html content here
</body>
Then it gives: Uncaught TypeError: window[("chatSocketSender1")] is undefined
Any suggestion please, why this not works with "onload" ?
The reason your code doesn't work is because in your first code var chatSocketSender1 creates a "global" variable (that's defined at the window level) that you later reference as window("chatSocketSender1"), but in the second code, var chatSocketSender1 is scoped to the anonymous event handler function, so is not available as window("chatSocketSender1").
Put another way:
<script>
var x = 1;
function foo() {
console.log(x)
}
</script>
works fine, but
<script>
function foo() {
var x = 1;
}
foo();
console.log(x);
</script>
will give an undefined variable error as x only exists inside foo. This isn't exactly what you've done, but is essentially the same concept.
Now, if your code was:
chatSocketSender1.send(
then it would have worked fine as your variable chatSocketSender1 is defined within the function() { onload event callback.
or instead of
var chatSocketSender1 =
you could do
window.chatSocketSender1 =
to define the variable globally, or you could:
<script>
var chatSocketSender1 = new WebSocket(...
function send() { ... }
$(window).on('load', function () {
document.querySelector('#send_button').onclick = ...
as you generally only need the event binding within the onload.
Related
I have the below code is working as long as I load the employee section and its scripts as part of the index.html
index.html Working Demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Employee Details loaded as usual and sript is executing able to see alert</h1>
</body>
</html>
Script.js
var empModule = (function (empModule) {
var Years = null;
$(document).ready(function () {
var empdata = { Name: 'Billa' }
var myVM = new empModule.viewModel(empdata);
});
empModule.viewModel = function (data) {
var that = this;
that.Name = data.Name;
alert(that.Name);
};
return {
empModule: empModule
}
} (empModule || {}));
Error Scenario:
We decide to move employee related section based on some condition. Hence we are loading this section and section related script(emp.js) via Ajax. But now it is throwing the error empModule.viewModel is not a constructor. Why is it so?
If I move the document.ready section at the bottom like the below order, it is working
Emp.js(moved from script.js to emp.js and load via ajax(
var empModule = (function (empModule) {
var Years = null;
// Code not working when we load this script file using Ajax.
// But works if we move this document.ready at bottom
//$(document).ready(function () {
// var empdata = { Name: 'Billa' }
// var myVM = new empModule.viewModel(empdata);
//});
empModule.viewModel = function (data) {
var that = this;
that.Name = data.Name;
alert(that.Name);
};
//Working only if I keep the ready section here
$(document).ready(function () {
var empdata = { Name: 'Billa' }
var myVM = new empModule.viewModel(empdata);
});
return {
empModule: empModule
}
} (empModule || {}));
The function empModule will get executed automatically as it is self
executing function. When it is executing it needs to prepare a
empModule.viewModel object, but failed to do that when viewModel
definition is located after document.ready (caller). This happens only
when I load this script via Ajax, but works if I pre load it in a page
This is because in the first example the script.js is part of the document and therefore the document.ready waits for that .js file to be loaded before trying to call empModule.viewModel().
In the second example, your script is loaded asyncronously, but the page is not taking this into account. So the page loads (without the script.js) and then you load the script.
At this point, the document is ready (as the ajax loaded script isn't part of the document) so the empModule.viewModel() call fires straight away, before the rest of the script (which is the bit that defines the function) and you get your error.
Just like #dougajmcdonald said is your issue, but your solution is, instead of loadding by AJAX, just insert the script tag in your document:
// Instead of $.ajax(... /myScript.js) use:
function loadMyScript(){
var script = document.createElement("script");
script.type = "text/javascript";
script.src = 'myScript.js';
script.onload = function() {
empModule.doSomething(); // or callback
};
}
My first code working but second code not working after adding () parenthesis after myFunction. What is the reason?
Code1
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction;
</script>
<h3 id="status"></h3>
Code 2
<script type="text/javascript">
function myFunction(){
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>
In first case you're assigning the reference of the function which will be used in callback.
In your second case you're assigning the value that is being returned by the function which is in this case undefined as you're not returing anything.
window.onload or any event handler for that matter, expects a function reference to be executed on callback.
window.onload is an event handler and must be a function, not the result of function. of course you may leave parenthesis, but in this way your function myFunction should return another function
<script type="text/javascript">
function myFunction(){
return function() {
var status = document.getElementById("status");
status.innerHTML = "The page finishing loading made my function run.";
}
}
window.onload = myFunction();
</script>
<h3 id="status"></h3>
So, the function "txtLoad()" will not execute while "txtFunc()" is being called by an onLoad function.
<!DOCTYPE html>
<html>
<head>
<title>Page</title>
</head>
<body>
<textarea id="Text" rows="20" cols="70"></textarea>
<script>
function txtFunc(){
var q=1;
}
function txtLoad() {
document.getElementById("Text").innerHTML = "Hello";
}
onload=function(){
txtLoad()
}
onload=function(){
txtFunc()
}
</script>
</body>
</html>
The JavaScript engine says there is nothing wrong with the code inside the "script" element. Does anyone know why the function isn't executing?
your second onload= replaced the function that calls txtLoad, if you want to run both:
onload = function () {
txtLoad();
txtFunc();
};
Also there seems to be extra "}" after the txtFunc.
How can two functions be defined to the onload. For eg:
var x = 1
var x = 2
What do you think the value of x is going to be? Obviously 2.
You are overwriting the onload. Its only going to execute the stuff which you assigned at last.
You could do this to achieve what you want.
onload = init()
function init() {
textLoad();
textFunc();
}
simply because the first onload was overwritten by the las onload.
function txtFunc(){
var q=1;
}
function txtLoad() {
document.getElementById("Text").innerHTML = "Hello";
}
onload=test();
function test()
{
txtLoad();
txtFunc();
}
If I implement the following JavaScript code block in HTML markup:
<script type="text/javascript">
function MyFunc() {
alert(1);
}
var f1 = MyFunc;
</script>
<script type="text/javascript">
function MyFunc() {
alert(2)
}
</script>
<script type="text/javascript">
f1();
</script>
I get an alert message '1'.
However, if I use the following code:
<script type="text/javascript">
function MyFunc() {
alert(1);
}
var f1 = MyFunc;
function MyFunc() {
alert(2)
}
</script>
<script type="text/javascript">
</script>
<script type="text/javascript">
f1();
</script>
I get '2'. Why?
Tested in IE10, latest FF, Chrome.
This is caused by hoisting. var and function declarations are hoisted to the top of the script block they are in.
This means that your first script essentially becomes:
var f1;
function MyFunc() {
alert(1);
}
f1 = MyFunc;
// new script block
function MyFunc() {
alert(2)
}
// new script block
f1(); // alert 1
Meanwhile, your second script becomes:
var f1;
function MyFunc() {
alert(1);
}
function MyFunc() { // overwrite previous MyFunc
alert(2)
}
f1 = MyFunc;
// new script block
f1(); // alert 2
I hope this makes sense - just in general avoid overwriting functions XD
Each script element is parsed and executed in order. In the first case, the assignment to f1 is made before the second declaration is processed.
In the second case, both declarations are parsed before the assignment is made (because declarations are processed before any code is executed), so the second declaration replaces the first before the assignment to f1.
I hope I don't confuse anybody, but, I suspect the answer has something to do with scopes.
Here is my argument:
For the 1st case:
<script type="text/javascript">
function MyFunc() {
alert(1);
}
var f1 = MyFunc;
window.foo1 = MyFunc;
</script>
<script type="text/javascript">
function MyFunc() {
alert(2)
}
window.foo2 = MyFunc;
</script>
<script type="text/javascript">
f1();
alert(window.foo2 === window.foo1);
</script>
The second alert will issue a false.
Now the 2nd case.
<script type="text/javascript">
function MyFunc() {
alert(1);
}
var f1 = MyFunc;
window.foo1 = f1;
function MyFunc() {
alert(2)
}
window.foo2 = MyFunc;
</script>
<script type="text/javascript">
</script>
<script type="text/javascript">
f1();
alert(window.foo1 === window.foo2);
</script>
The second alert will issue a true.
It kind of shows that (for 1st case) MyFunc is redefined and is a totally different "object" when the 2nd script block is processed. f1 holds a reference to the first "object" in the first script block. Hence f1() alerts 1.
For the first part with alert message 1 the declaration var f1 = MyFunc; becomes similar to a local wrt different <script> blocks.Hence the <script> block in which var f1 is defined it performs the function contained in that block.
For the second part with alert message 2 , 1st MyFunc() is overwritten by the second.
I have used google feed API to read a Rss feed url and display the title. When I call the function get_rss1_feeds directly It works fine. But when I call it with setTimeout or setInterval I am able to see only blank screen and the page does not stop loading!!
<script src="http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0" type="text/javascript"></script>
<script type="text/javascript" src="jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="query.mobile-1.0a4.1.min.js"></script>
<script type="text/javascript" src="jsRss.js"></script>
<script type="text/javascript" src="notification.js"></script>
My notification.js
/** global variable **/
var Rsstitle;
/** end global variable **/
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
// Empty
}
function get_rss1_feeds() {
console.log('test'); // this is being outputted
var Rss1_title = getRss("http://yofreesamples.com/category/free-coupons/feed/?type=rss", function(entry_title) {
if(Rsstitle != entry_title)
Rsstitle = entry_title;
console.log('test1',Rsstitle); // not working
});
}
//get_rss1_feeds() works fine
setTimeout(get_rss1_feeds,5000);
My jsRss.js file
function getRss(url, callback){
console.log('test2'); // this is being outputted
if(url == null) return false;
google.load("feeds", "1");
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
var entry = result.feed.entries[0];
var entry_title = entry.title; // need to get this value
callback && callback(entry_title);
}
}
function Load() {
// Create a feed instance that will grab feed.
var feed = new google.feeds.Feed(url);
// Calling load sends the request off. It requires a callback function.
feed.load(feedLoaded);
}
google.setOnLoadCallback(Load);
}
You need to set a breakpoint in the getRss() function and see what's going on when it's called from setTimeout(). My guess would be that something in that function has a scoping issue and isn't available from the global scope that setTimeout runs in, but is available from the normal scope you tried it in. It could be variables or it could be functions that aren't available.
This can sometimes happen if functions are declared inside another function and thus aren't actually available globally.
FYI, this block of code is very odd:
var Rsstitle;
if(Rsstitle != entry_title)
Rsstitle = entry_title;
You can replace it with this:
var Rsstitle = entry_title;