I have an external JavaScript src which I want to add a loading animation until it's finish loading:
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
I'm currently using jQuery (window).load, but its waiting until all page is fully loaded, I want to wait only for that specific code:
<script>$(window).load(function(){$(".loadingif").hide();});</script>
Update:
This is my code as you have suggested, it's is not working, what I'm doing wrong---
some text.....
<span class="loading-gif"></span>
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
<script>hideLoading();</script>
some text.....
<script>function hideLoading(){$(".loading-gif").hide();}</script>
Hopefully this works:
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
<script type="text/javascript">
hideLoadingThingy();
</script>
The second script should run after the first one finishes loading. This is because it is included after the first one, so the first one is loaded first.
Unless the methods in xxx.js are called asynchronously, your browser will only execute one task at a time. Read more about that here
Update:
Use this:
some text 2.....
<span class="loading-gif"></span>
<script src="https://xxxx.domain.com/xxx.js" type="text/javascript"></script>
<script type="text/javascript">$(".loading-gif").hide();</script>
some text 2.....
You could key off of the expected javascript object that will be loaded into global scope:
(function checkValue(){
if (libraryValue === undefined){
setTimeout(checkValue, 100);
} else {
$(".loadingif").hide();
}
})();
I would use Feathercrown's solution unless you choose to load that library asynchronously.
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
I'm new to web development, and was having issues with two plug-ins. I already found a workaround to solve it, but I'm not convinced at all about what I did, so I ask you guys if you can enlighten me on what is this about.
The page in question uses SlimScroll and DataTables plugins. At first, I had an HTML file like this one.
<body>
<!-- STUFF -->
<!-- SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="plugins/slimScroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="plugins/DataTables/datatables.min.js" type="text/javascript"></script>
<script src="assets/scripts/tablas.js" type="text/javascript"></script>
<script src="assets/scripts/general.js" type="text/javascript"></script>
At the bottom, general.js is used to handle click events and other stuff, and tablas.js has the code that picks up a file with data and displays it in DataTables. The relevant code from general.js:
$(document).ready(function() {
$('#contenedor-menu').slimScroll({
height: '100%'
});});
And the code for tablas.js:
$(document).ready(function() {
$('#tablita').DataTable( {
"ajax": 'data/COut2.txt',
} );});
With this structure, when I load the page, SlimScroll fails with the message in the console: "TypeError: $(...).slimScroll is not a function"
Then after touching around, I switched the order of the scripts in the HTML file. I put datatables first and then slimscroll.
<script src="plugins/DataTables/datatables.min.js" type="text/javascript"></script>
<script src="plugins/slimScroll/jquery.slimscroll.min.js" type="text/javascript"></script>
And now it works ok, with no errors.
Could somebody please explain to me what's going on?
Thanks in advance!
The use of multiple $(document).ready(function() { } is the main cause of this issue. There should be only one Document Ready event handler.
You may try using the pageLoad() function or onLoad() events
Not positive but it is usually best practice to put the scripts you absolutely need before everything else in the head. This is so that the content of the page does not finish loading until all the dependencies have been loaded first.
By reordering your scripts you may have a solution that will only work some of the time.
Put all the scripts you need to load in the head and your general.js script at the end of your body element.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="a.js"></script>
</head>
<body>
<script>
functionFromAJS();
</script>
</body>
</html>
this works OK most of the time, but on production server, its not 100%. It says that functionFromAJS() doesnt exists, which is ok, if the .js is not gets loaded in time. But then what to do?
EDIT: Using the window.onload function should not do any difference as long as the script you're embedding is loaded before the function call. Then the a.js file will be loaded before <script>functionFromAJS();</script> anyway and you should be able to execute the function if it exists.
Try using:
<script>
window.onload = function() {
functionFromAJS();
};
</script>
So that the function is not called before the document is fully loaded.
Or if you're using jQuery you can use:
<script>
$(document).ready(function() {
functionFromAJS();
});
</script>
If the function doesn't exist, then it's not a matter of the file not being loaded in time, then the file isn't loaded at all.
When the browser encounters a script tag for loading a file, then it will stop the parsing of the page until the file has been loaded, or until the file fails to load. The functionFromAJS will never be called before the browser has completed the attempt to load the file.
If the file fails to load, then there isn't much you can do. You can check if the function exists before you call it to avoid the error. You could even try to load the script again, but if it failed the first time then it's likely that it will still fail.
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.
I am trying to call a function that, on the load of the script above it, will run some JavaScript.
<script src="../Layout/jquery.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" src="helperscript.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var itemid = '1';
if(itemid)
{
idselect(itemid);
}
})
</script>
helperscript.js contains the function idselect.
When I load the page I get an error saying that 'idselect is undefined', even though it is in the above file. I suspect that this is due to helperscript not being fully loaded yet, but that is just a hunch.
Can anyone help me?
Scripts load in order and are blocking.
There must be a problem with the loading of the script, not the timing.
Most likely you have either a mistake in the URL (resulting in a 404) or a JavaScript error (which would show up on the error console)
I don't think your hunch is right, because this script tag:
<script type="text/javascript" language="javascript" src="helperscript.js"></script>
should block any other javascript from executing until helperscript.js is downloaded and executed.
Use jQuery.getScript() and register a success function. It will be safe to use idselect on or after the success function is executed.
http://api.jquery.com/jQuery.getScript/
Make sure your path to the script to the .js file is correct.
Also cut the language="javascript" part.