Javascript loaded check through jquery getscript - javascript

I want to load a Javascript file on the click event instead of loading at the page load event, for performance reasons.
Is there anyway to know that particular if javascript is already loaded?
Right now I am maintaining a global variable to check the 'loaded' event
var javascriptLoaded=false
if (!javascriptLoaded)
$.getScript('/scripts/test.js', function() {
javascriptLoaded = true;
setTimeout(function() {
callSomeFunctionhere();
}, 1000);
});
Is there any better way of doing this?

Yes. What you want to do is use the success callback. A call back method which will only be called once the ajax request to load the script has successfully finished. For example this is equivalent:
$.ajax({
url: "/myscript.js",
dataType: "script",
success: function(){
scriptLoaded = true;
//do some more stuff now that the script is loaded
}
failure: function(){
scriptLoaded = false;
}
});

A simple way to check if a script has been loaded is to see if that script is callable:
if($.fn.foo == undefined) {
$.getScript("/path/to/script/foo.js", function() {
// success
});
}

Related

execute js function when a function inside document.ready is done

I have a website which computes the performance of each server. One of the requirements is the center partial page which are about performances must be finish loading first before doing another function in the background.
This center partial page uses ajax calls. They are being defined at the document.ready of the js file:
$(document).ready(function () {
// ajax call here
// another ajax call here
// third ajax call here
});
Then the function that I wanted to execute after the function inside the document ready is done:
function functionA() {
// some codes here
});
I tried using this:
$.when(document).ready(function () {
}).done(functionA);
but I can't make it run .. Any suggestions would be gladly appreciated. Thanks in advance!
The first letter in AJAX stands for asynchronous which means that at the end of your document.ready event, they could be off somewhere else doing some processing. The document.ready will not wait for them to finish.
You need to set up jQuery using .when to tell you when all three AJAX calls are complete:
// Document.ready
$(function() {
// Any synchronous code you may do on DOM ready goes here
// Set up the promise
$.when(
// Pass in all your AJAX calls.
$.ajax({ url: "/AjaxCall1?param=true" }),
$.ajax({ url: "/AjaxCall2?param=1" }),
$.ajax({ url: "/AjaxCall3?param=yup" })
).then(function() {
console.log("All AJAX requests finished");
}, function() {
console.log("Something went wrong :(");
});
});
Here is a way to deal with DOM ready event and Ajax calls at the same time :
var init, ajax1, ajax2, domready;
ajax1 = $.ajax({ url: '/1' });
ajax2 = $.ajax({ url: '/2' });
domready = $.Deferred();
$(domready.resolve);
init = $.when(domready, ajax1, ajax2);
http://api.jquery.com/category/deferred-object/
Then you don't need to care about the code above any longer :
init.done(function () { alert('success'); });
init.fail(function () { alert('failure'); });
init.done(function ($, response1, response2) {
alert(response2[0]); // shows the data from the second Ajax call
});
Here is a live demo : http://jsfiddle.net/wared/s22dT/.
About your try, jQuery.when() returns a Promise object which has no ready method :
$.when().ready() // TypeError: Object #<Object> has no method 'ready'
http://api.jquery.com/jQuery.when/

Unexpected javascript function behaviour

What I want is to add a loader bar to my HTML, while my method does some time consuming AJAX calls and DOM manipulation.
The problem is, that show() method won't show the loader bar until the AJAX calls are done, how do I fix this?
I want to force the show() method, then do AJAX calls and DOM stuff, then force the hide() method.
Method doing AJAX calls:
$('.my-button').on('click', function(){
$('#display-loader').show();
// ajax and dom manipulation
$('#display-loader').hide();
});
EDIT: Seems like there's some misunderstanding as to what my problem is. If I change my code to this:
$('.my-button').on('click', function(){
$('#display-loader').show();
// ajax and dom manipulation
});
It still won't SHOW the loader bar, untill the AJAX methods are done, it's like it skips the show() method, does AJAX stuff, and then calls the show() afterwards.
All the AJAX calls have async set to false. I have 5 AJAX calls, and each AJAX call relies on the data fetched from the previous call, I have no way to set the async to true, is there a way to get around this, and force the DOM to display the image, and then do AJAX calls?
you can do next:
showLoader();
$.ajax({
type : 'POST',
url : url,
data : postData,
success : function (returnData) {
},
error : function (xhr, textStatus, errorThrown) {
},
complete : function (){
hideLoader();
}
});
You need to call hideLoader() within AJAX success function, to hide after ajax operation. As AJAX is asynchronous, so in your code hideLoader() execute before finish ajax call and done dom stuff.
$('.my-button').on('click', function(){
showLoader();
$.ajax({
....
success: function() {
hideLoader();
}
});
});
according to #Esailija comment to hide after complete callback do like:
$('.my-button').on('click', function(){
showLoader();
$.ajax({
....,
success: function(){
},
complete: function() {
hideLoader();
}
})
});
I recommend maybe the following way:
$.ajax({
.....
}).done(function () {
hideLoader();
});
This will insure the loader goes away. If your ajax isn't successful then the success callback will never be reached and then the loader will stay on the page.
But it depends on the scenario. You can also just put it in your error callback.

How to do asyncrhonous jQuery.get() before $(window).load()?

I want a SVG file to be loaded in a variable before $(window).load() will be fired.
I load the file using jQuery.get(). The problem is, that this function works asynchronously and by the time, when the SVG file is read, the $(window).load() is already invoked.
So I have following code:
var data;
$(document).ready(function () {
jQuery.get(
"my.svg",
function (_data) {
data = _data;
},
'text');
});
$(window).load( function () {
alert(data);
});
The alert will show "undefined". If it will be invoked later (after 5 seconds for example) then it will show the content of the SVG file.
Any suggestions? Thanks!
I agree that setInterval would probably be the solution you want IF you want to do stuff the hard way because you can never tell how long an AJAX request is going to take.
I would recommend restructuring your code to be more like this:
<script>
$(document).ready(function () {
//this can remain async: TRUE
jQuery.get(
"my.svg",
function (_data) {
//call function to do something to svg file
//if you are relying on the SVG to be there in order to call an action
//then why not wait for the SVG to load first and then call the action
svgAction(_data);
},
'text');
function svgAction(img_code){
//do something with img code now
}
});
</script>

reload jquery and js library

I reload my page using an updatepanel. In my masterpage I do the following.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script src="App_Themes/Project/js/core.js"></script>
<script src="App_Themes/Project/js/libs/modernizr-1.6.min.js"></script>
When I partially reload a page with ajax (updatepanels), this files are nog loaded. So an slider is impossible to use.
Is there a way to load this files when I do a Ajax call?
You can use this function:
function ReloadScripts() {
var scriptTag = document.getElementsByTagName('script');
var src;
for (var i = 0; i < scriptTag.length; i++) {
src = scriptTag[i].src;
scriptTag[i].parentNode.removeChild(scriptTag[i]);
try {
var x = document.createElement('script');
x.type = 'text/javascript';
x.src = src;
//console.log(x)
document.getElementsByTagName('head')[0].appendChild(x);
}
catch (e) {}
}
};​
On ajax call success method, just call this function
$.ajax({
type:"POST",
dataType: 'json',
error: function(data) {
//do error stuff
},
success: function(data) {
//do success stuff
// at last call this
ReloadScripts();
}
});
Put all your initialization/re-initialization code in a js function call pageLoad(), it gets called on all async postbacks:
function pageLoad()
{
//do work
}
$(document).ready() and pageLoad() are not the same!
I think what you need is not to reload the js libraries, you need to call the exact function that applies some property to the some elements which are loaded by your ajax call.
For example:
Your ajax appends some links to page like
<a id="someLink">link</a>
And there is a code that colors this element into blue at a method inside a js library like:
function colorBlue() {
$("a").css("color", "blue");
}
So here you do not need to reload whole libraries, just call this function after your ajax call:
function makeAjax() {
//here some ajax method is executed
colorBlue();
}
And that's it, your needed changes are done inside the library method.
PS: You can find which method applies the specific work to your elements by searching the class, tag name or id of the target elements inside js library. There you

How to extract ajax response data from the success callback

Sorry if this is a duplicate but I couldn't find any satisfying answers in the previous posts.
$(function() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
// Data received here
}
});
});
[or]
someFunction() {
return $.ajax({
// Call and receive data
});
}
var myVariable;
someFunction().done(function(data) {
myVariable = data;
// Do stuff with myVariable
});
The above code works just fine. However, this ajax request is made on page load and I want to process this data later on. I know I can include the processing logic inside the callback but I don't want to do that. Assigning the response to a global variable is not working either because of the asynchronous nature of the call.
In both the above ways, the 'data' is confined either to the success callback or the done callback and I want to access it outside of these if possible. This was previously possible with jQuery 'async:false' flag but this is deprecated in jQuery 1.8.
Any suggestions are appreciated. Thank you.
You can "outsource" the callback to a normal function, so you can put it somewhere, you like it:
$(function() {
$.ajax({
url: 'ajax/test.html',
success: yourOwnCallback
});
});
somehwere else you can define your callback
function yourOwnCallback(data) {
// Data received and processed here
}
this is even possible with object methods as well
This solution might not be idea but I hope it helps.
Set the variable upon callback.
Wherever you need to process the data, check if variable is set and if not wait somehow.
Try:
$(document).ready(function(){
var myVar = false;
$.ajax({
url: 'ajax/test.html',
success: function(data) {
myVar=data;
}
});
someFunction(){ //this is invoked when you need processing
while(myVar==false){}
... do some other stuff ..
}
});
Or
someFunction(){
if(myVar==false){
setTimeout(someFunction(),100); //try again in 100ms
return;
}
.. do some other stuff ..
}

Categories