So I am having this document:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
//executes when HTML-Document is loaded and DOM is ready
alert("document is ready");
});
$(window).on("load", function () {
//executes when HTML-Document is loaded and DOM is ready
alert("window is loaded");
});
</script>
</body>
</html>
Note the inline comments inside the 2 function calls.
Apparently these do NOT work and give me an error:
SyntaxError: missing } after function body[Weitere Informationen] index:1:297 note: { opened at line 1, column 37
However using a multiline comment /* */ is working just perfectly.
I`m assuming, that the single line comments dont work becuase somehow the javascript gets minified into one line.
Can sombody evaluate an how this is happening?
Where can you use single line comments and where not?
Or is it just generally a bad idea to use single line comments in js?
Because after minifying everything is just one line, a single line comment, which doesn't have an end-of-comment tag, doesn't work.
Related
I offen heard that loading jquery as last element is a good idea because this way a web page loads faster. At the same time I have a script in the header which shows error:
$(document).ready(function () {// Uncaught ReferenceError: $ is not defined
...
}
Should I move jquery loader before the script or I need to change this script some way?
Your concrete issue stems from the fact that you execute statements that use jQuery (i.e. they execute $, which is a function in the jQuery library, also called "the jQuery function" because jQuery is an alias) before it is loaded.
True, it is typically recommended to load scripts last, but that still means the scripts have to be loaded in the correct order, with usually jQuery before your own scripts using jQuery.
If you really want to load your own scripts before jQuery for some reason, you need to defer its execution and have a third helper script to run it, e.g.:
// script.js
(function() {
function myLibraryMainFn() {
$('div').text('simulating work, utilizing jQuery');
}
window.myNamespace = {
run: function() {
myLibraryMainFn()
}
};
}());
<!DOCTYPE html>
<html>
<body>
<div></div>
<script src="script.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
// Run your script now:
window.myNamespace.run();
</script>
</body>
</html>
Always refer library file first(in your case jQuery), then use it next..For page load and performance add it before body end tags of your HTML
HI i am facing some problem while calling function from index.html on load event
it return error readjson is not defined in console.
index.html
<script type="text/javascript">
$(window).load(function () {
readjson('a','s');
});
</script>
main.js file
<script type="text/javascript">
function readjson(val1,val2){
//some code
}
</script>
Can anyone tell me why it is not able to call, i have link main.js file to index.html
JavaScript files shouldn't include any HTML.
Remove <script type="text/javascript"> and </script> from main.js.
You should see an error when that file is loaded (along the lines of Unexpected token <).
Call it like this inside the js file without the "script" tag :
function readjson(val1,val2){
//some code
}
In index.html you need the "script"
And follow the advice given in the comments, always include first the .js file and then the function in the index.html
Did you add jquery link properly??
If not, you should add jquery link for $(window) to be called. such as..
<script src="http://code.jquery.com/jquery-latest.js"></script>
If you actually have two script declarations as you are showing here the the window load will fire first. It then look for your function, which has not been created yet. That's why you are getting undefined.
You could have one script declaration on the page and place your function in the load function.
<script>
$(window).load(function () {
readjson('a','s');
function readjson(val1,val2){
//some code
}
});
</script>
Remove tags from main.js:
<script type="text/javascript"> and </script>
and remember to include jquery and main.js with:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"></script>
<script src="test.js"></script>
So, lets say you have a page that wants to load from a javascript file and it includes
temp.html file
<script src="example.js"></script>
<p class="one"></p>
Now in the example.js file you have a function that is
function getInfo() {
var place = "foo"
$(".one").html(place);
}
//Edit currently I call the function inside the JS file
getInfo();
My question is how would you connect the two files so that the external javascript file knows that it is pointed to the paragraph with the class one?
Normally when this is in a single page, you would call the function and the info will be set.
I have seen a getScript method and a load method for Jquery. Would that be applicable here?
Any ideas on how to approach this? If you provide some code that will be super helpful.
Thanks in advance.
Looks like you want to execute getInfo() as soon as it's defined (i.e.: example.js is loaded).
You can try this approach:
<script src="example.js" onload="getInfo();"></script>
In your example.js, change getInfo() to something like this:
function getInfo() {
$(document).ready(function() {
var place = "foo"
$(".one").html(place);
});
}
Your language is confusing, but you could use jQuery's $(document).ready function which would suffice. Generally speaking, an externally loaded file should execute where the tag is in the script.
A hack could be to place a tag before the end of your document body, give it an id, and then use $('#id').ready() there. In general though, you could just try coding the transclusion concept (I'm guessing you're used to this) from scratch using intervals and timeouts.
<div id="rdy">
</div>
</body>
Then in your file:
$('#rdy').ready(getInfo);
Just my added opinion, you should consider that Google is up to some not-so-nice things these days, they are long-gone from the "do no evil" mantra.
If we assume you have a JavaScript file that contains this content:
function getInfo() {
var place = "foo"
$(".one").html(place);
}
then your markup will look something like this:
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="example.js"></script>
<script>
$(function(){
getInfo();
});
</script>
</head>
<body>
<p class="one"></p>
</body>
</html>
$(function(){ ... }); is just the simplified version of $(document).ready(function(){ ... });. They both more or less handle the onload event, which fires when page has finished loading.
Never met this problem, and don't know why.
The only explanation is a scope issue.
In the same page, I have 2 sections of JS :
...
<script type="text/javascript">
go();
</script>
<script type="text/javascript">
function go()
{ alert(''); }
</script>
...
This will show an error : go is not defined
where
...
<script type="text/javascript">
go();
function go()
{ alert(''); }
</script>
...
is working (obviously).
Does <script> tag creates a scope of JS ?
help ?
This isn't a scope issue. If you define a function (in the global scope) in one script element, then you can use it in another.
However, script elements are parsed and executed as they are encountered.
Hoisting won't work across script elements. A function defined in a later script element won't be available during the initial run of an earlier script element.
You either need to swap the order of your script elements, or delay the function call until after the script that defines it has run (e.g. by attaching it to an onload event handler).
<script>
function go() {
alert('');
}
</script>
<script>
go();
</script>
or
<script>
window.addEventListener("load", function () {
go();
}, false);
</script>
<script>
function go() {
alert('');
}
</script>
The html parser stops to execute your script before moving to next elements. So the next script element
is not executed until the first one is executed.
This is comparable to:
<script>
document.getElementById("hello") //null because the html parser hasn't met the div yet.
</script>
<div id="hello"></div>
The other cause of this as an apparent error is if the first script block has a syntax error and is rejected in its entirety, but the second block runs on and misses its buddy code.
As it's been said already, order matters. For what it's worth, I saw this issue with an experiment (not production!) where I had something like this:
<head>
<script src="/path/one.js" defer>
</head>
<body>
<script>
methodInOneJs();
</script>
</body>
And the browser complained with a ReferenceError, even though methodInOneJs() was defined in one.js. This because of the defer attribute in the script that loads it. One might think that putting defer in the inline script as well would solve the issue, but according to MDN:
Warning: This attribute must not be used if the src attribute is
absent (i.e. for inline scripts), in this case it would have no
effect.
One quick solution (aside from removing defer altogether) was to use the onload event (again, not production, where I'd just use src):
<head>
<script src="/path/one.js" defer>
</head>
<body onload="run();">
<script>
function run()
{
methodInOneJs();
}
</script>
</body>
This is because with defer:
the script is meant to be executed after the document has been parsed,
but before firing DOMContentLoaded.
Emphasis on "before firing DOMContentLoaded". See also how to load scripts last.
I've been sifting around the web trying to find out whats going on here and I have not been able to get a concrete answer.
I have one $(document).ready on my site that seams to run multiple times regardless of the code that is inside it.
I've read up on the bug reports for jQuery about how the .ready event will fire twice if you have an exception that occurs within your statement. However even when I have the following code it still runs twice:
$(document).ready(function() {
try{
console.log('ready');
}
catch(e){
console.log(e);
}
});
In the console all I see is "ready" logged twice. Is it possible that another .ready with an exception in it would cause an issue? My understanding was that all .ready tags were independent of each other, but I cannot seem to find where this is coming into play?
Here is the head block for the site:
<head>
<title>${path.title}</title>
<meta name="Description" content="${path.description}" />
<link href="${cssHost}${path.pathCss}" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="media/js/fancybox/jquery.fancybox.pack.js" type="text/javascript" ><!-- --></script>
<script src="/media/es/jobsite/js/landing.js" type="text/javascript" ><!-- --></script>
<script src="/media/es/jobsite/js/functions.js" type="text/javascript"><!-- --> </script>
<script src="/media/es/jobsite/js/jobParsing.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="/media/es/jobsite/js/queryNormilization.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery/jquery.metadata.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery/jquery.form.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js" type="text/javascript" charset="utf-8"><!----></script>
<script src="${jsHost}/js/jquery.i18n.properties-min.js" type="text/javascript" charset="utf-8"><!----></script>
<script type="text/javascript" charset="utf-8">
function updateBannerLink() {
var s4 = location.hash.substring(1);
$("#banner").attr('href','http://INTELATRACKING.ORG/?a=12240&c=29258&s4='+s4+'&s5=^');
}
</script>
</head>
Pay no attention to the JSP variables, but as you can see i'm only calling the functions.js file once (which is where the .ready function exists)
The ready event cannot fire twice. What is more than likely happening is you have code that is moving or manipulating the element that the code is contained within which causes the browser to re-execute the script block.
This can be avoided by including script tags in the <head> or before the closing </body> tag and not using $('body').wrapInner();. using $('body').html($('body').html().replace(...)); has the same effect.
It happened to me also, but I realized that the script had been included twice because of a bad merge.
This happened to me when using KendoUI... invoking a popup window would cause the document.ready event to fire multiple times. The easy solution is to set a global flag so that it only runs once:
var pageInitialized = false;
$(function()
{
if(pageInitialized) return;
pageInitialized = true;
// Put your init logic here.
});
It's sort of hack-ish, but it works.
Make sure you don't include JS file twice. That was my case
You might consider to use
window.onload
instead of
$(document).ready
try putting this in your functions.js to prevent it from being executed twice :
var checkit = window.check_var;
if(checkit === undefined){ //file never entered. the global var was not set.
window.check_var = 1;
}
else {
//your functions.js content
}
however i suggest that you look more into it to see where are you calling the second time.
I had a similar problem when I was trying to refresh a partial. I called a return ActionResult instead of a return PartialViewResult. The ActionResult caused my ready() to run twice.
There is a possibility to encounter this problem when you add same controller twice in the html.
For an instance:
[js]
app.controller('AppCtrl', function ($scope) {
$(document).ready(function () {
alert("Hello");
//this will call twice
});
});
[html]
//controller mentioned for the first time
<md-content ng-controller="AppCtrl">
//some thing
</md-content>
//same controller mentioned again
<md-content ng-controller="AppCtrl">
//some thing
</md-content>
I had a similar issue today. A <button type="submit"> caused the $(document).ready(...) event to fire again in my case. Changing the code to <button type="button"> solved the issue for me.
See document.ready function called again after submit button? here on stackoverflow for more details.
In my case $(document).ready was firing twice because of bad CSS, check if any part of your CSS has background-image: url('');
If the iframe doesnt show anything and is used for other reasons (like uploading a file without reload) you can do something like this :
<iframe id="upload_target" name="upload_target" style="width:0;height:0;border:0px solid #fff;"></iframe>
Notice that src is not included that prevents the second on ready trigger on the document.
I had this problem with window.load function was executed twice:
The reason was because I had reference to the same javascript-file in the main page as well as a .net usercontrol. When I removed the reference in the main page, the load-function was only executed once.
I had this happen to me this morning... and what I discovered after closely examining some html code in a jquery modal form that I had recently manipulated, that I'd accidentally removed a closing table tag. I haven't taken the time yet to fully understand why that caused the document.ready function to be called twice, but it did. Adding the closing table tag fixed this issue.
jQuery JavaScript Library v1.8.3 (yes, it is a legacy app)
My problem was that I had tags referencing my JS file in both my index.cshtml file AND my _Layout.cshtml. This was causing the document.ready function to fire twice, which was causing DataTables to bomb.