<!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.
Related
I the defer attribute of the script tag in the <head> section of HTML files. This almost always means that I cannot run js functions in the HTML since the js file is only loaded after the HTML file has been loaded..
I have run into a situation where I needed to run a js function in my HTML file, but would not want to remove the defer attribute from the script tag because of other functions in the js file. I looked at the possibility of using async, but it also was not helpful.
Any idea on how this could be done... other than using defer? I would still like to keep the script tag in the head, but going that way would mean that I have no open (non-function based) instructions in the linked js file... which is not always ideal.
Here is a sample of the HTML file
temp.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="temp.js" defer></script>
<title>Defer et al</title>
</head>
<body>
<script>
runThisFunction('Home');
</script>
</body>
</html>
And here is a sample of the js file
temp.js
function runThisFunction(varin) {
console.log(varin);
}
If I remove the defer from the js file, the function will run; if I leave it there, or use async instead, the function will not run because it has not loaded yet.
Any assistance in this small issue will be appreciated.
The best way to do this would be to refactor your script to contain an entry point in a function, and run that function once the DOM loads. Instead of, for example
// temp.js
function runThisFunction(varin) {
console.log(varin);
}
document.querySelector('.foo').textContent = 'doing stuff';
// other code here
put all of the functionality that depends on the page being loaded into its own function:
// temp.js
function runThisFunction(varin) {
console.log(varin);
}
function init() {
document.querySelector('.foo').textContent = 'doing stuff';
// other code here
}
window.addEventListener('DOMContentLoaded', init);
This way, if you also remove the defer attribute, runThisFunction will be available immediately, but the other parts of your code won't run until the page is loaded.
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.
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
On my index.html I am doing the following:
<script src="jquery/jquery.js"></script>
<script src="managment.js"></script>
<script src="jquery/jquery.mobile-1.1.0.js"></script>
After doing some calculation, I have the need of using a function from the managment.js file:
$.getScript("managment.js", function(){
alert("Script loaded and executed.");
login();
});
}
And finally the managment.js file:
<script type="text/javascript">
function login(){
alert("asdasdasdasdasdasd");
}
</script>
My issue, is that the login() function is never called. Actually the alert I have inside getScriptfunction is not called either, but the strange thing is that if I check if the jquery.js file is loaded the alert is called. More, if I try to call login() without doing getScriptnothing happens has expected. My files structure is the following:
(note: you can see that I am using 2 managment.js files. I tried both approaches to see if the problem was with the path of the file.)
What am I missing here? For relevance, I am using PhoneGap, but this isn't working on the browser as well.
The management.js file should not contain the <script type="text/javascript"> tag. It should be:
function login(){
alert("asdasdasdasdasdasd");
}
Hope it helps! :)
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.