show loading gif until script has loaded - javascript

I would like to display a loader icon gif until the script is totally loaded, is it possible?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<img src="loading.gif">
I think it is necessary to use jquery. but I do not know how to do. could someone help me?

Display image <img src="loading.gif">
On dom-ready remove element.
$(document).ready(function () {
$('img').remove();
})

Can be done even without jQuery:
<img id="loading" src="loading.gif">
<script onload="javascript:document.getElementById('loading').style.display='none'" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>

Yes you can. You can use this function which loads a script and fires a callback. In your callback, you hide the gif.
function loadScript( url, callback) {
var script = document.createElement( "script" )
script.type = "text/javascript";
if(script.readyState) { //IE
script.onreadystatechange = function() {
if ( script.readyState === "loaded" || script.readyState === "complete" ) {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function() {
callback();
};
}
script.src = url;
document.getElementsByTagName( "head" )[0].appendChild( script );
}
So, in your HTML place your gif showing up initially. And, add this code at your onload function:
<script>
window.onload = function(){
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js', function(){
$('.gif-selector').hide();
})
}
</script>
Edit: This is a more complex solution than others provided, maybe if your goal is something pretty simple you should use some of the others. Still, this function works great and I have used it in many of my projects. It's best thing is that you can chose to load the script whenever you want to

Related

Load jquery dynamically before using jquery

My script will be using as widget in third-party website so i don't aware about jquery loaded and which version of jquery loaded or not at third-party end.
So Before loading below script i want to check is there already latest jquery 1.11.1 loaded after dom ready if not then i want to load the jquery latest and run below script.
script.js
var $ = jQuery.noConflict( true );
(function( $ ) {
$(document).ready(function() {
alert("Document Ready ");
});
})($jy);
EDIT 1
var addNewJQuery = function() {
(function( $ ) {
$jy = $;
var invokeOriginalScript;
$(document).ready(function() {
......my code here.....
}):
})(jQuery);
}
Not sure if this is working for you, but it looks like it is working.
Maybe you need to remove the other script from your header after you loaded the second jQuery file. But it seems to work with both scripts loaded.
I've also added a check if jQuery is loaded at all, if not it will load jQuery.
You can also find the same code in this fiddle.
var addNewJQuery = function() {
//var jQ = jQuery.noConflict(true);
(function ($) {
$(document).ready(function () {
alert("You are now running jQuery version: " + $.fn.jquery);
});
})(jQuery);
};
if ( typeof jQuery === 'undefined' ) {
alert('no jQuery loaded');
//throw new Error("Something went badly wrong!"); // now you could load jQuery
loadScript('https://code.jquery.com/jquery-1.11.2.js', addNewJQuery);
}
if ($.fn.jquery !== '1.11.2') {
console.log('detected other jQuery version: ', $.fn.jquery);
loadScript('https://code.jquery.com/jquery-1.11.2.js', addNewJQuery);
}
function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

How to include jQuery dynamically in any website using pure javascript

I am trying to include jquery dynamically and i have used the following code-
index.php
<!doctype html>
<html>
<head>
<script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>
<script type="text/javascript">
$(document).ready(function(){
$('#testing').html('<p>This is a paragraph!</p>');
});
</script>
</body>
</html>
includejquery.js
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.async = true;
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
jQuery.noConflict();
}
But jquery functionality is not working it is not printing the paragraph tag :-( Please help me out. Thanks in advance
That's not working because your $(document).ready(... line runs before jQuery loads, and so it fails because either $ is undefined (throwing a ReferenceError) or it refers to something other than jQuery. Also, you're calling jQuery.noConflict() before jQuery is loaded, and if that call did work, it would mean that $ no longer referred to jQuery at all, so $(document).ready(... still wouldn't work.
In any modern browser, you can use the load event on the script element you're adding, which tells you that the script has been loaded. Probably best to pass a callback into a call you make to includejquery.js, like this:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="includejquery.js"></script>
</head>
<body>
<div id="testing"></div>
<script type="text/javascript">
includejQuery(function($){
$('#testing').html('<p>This is a paragraph!</p>');
});
</script>
</body>
</html>
includejquery.js:
function includejQuery(callback) {
if(window.jQuery)
{
// jQuery is already loaded, set up an asynchronous call
// to the callback if any
if (callback)
{
setTimeout(function() {
callback(jQuery);
}, 0);
}
}
else
{
// jQuery not loaded, load it and when it loads call
// noConflict and the callback (if any).
var script = document.createElement('script');
script.onload = function() {
jQuery.noConflict();
if (callback) {
callback(jQuery);
}
};
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
}
}
Changes there:
In includejquery.js, just define a function and wait to be called.
Have that function accept a callback.
Have it wait for the script to load.
When the script is loaded, call jQuery.noConflict and then, if there's a callback, call it and pass in the jQuery function.
In the HTML, I'm calling the function, and receiving the argument it passes me as $, so within that function only, $ === jQuery even though outside it, it doesn't (because of noConflict).
What's wrong with the implementation from the HTML5-Boilerplate?
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery_2.1.1.min.js"><\/script>')</script>
Alternative solution
(function () {
initScript().then(function (v) {
console.info(v);
var script = document.getElementById("__jquery");
script.onload = function () {
$(document).ready(function () {
// Main logic goes here.
$("body").css("background-color","gray");
});
};
});
function initScript() {
promise = new Promise(function(resolve,reject) {
try {
if(typeof jQuery == 'undefined') {
console.warn("jQuery doesn't exists");
var jQuery_script = document.createElement("script");
jQuery_script.src = "https://code.jquery.com/jquery-2.2.4.min.js";
jQuery_script.type = 'text/javascript';
jQuery_script.id = "__jquery";
document.head.appendChild(jQuery_script);
resolve("jQuery added succesfully.");
}
resolve("jQuery exists.")
} catch (ex) {
reject("Something went wrong on initScript() : ", ex);
}
});
return promise;
}
})();
I used promise because if there is no jQuery in the page we need to wait to load it first.
.ready will not fire since your script loads async.
This should the first thing to run on the page and block all other scripts in order to load the dependencies on time.
Appending to body:
function loadScript() {
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.mydomain/myscript.js';
script.async = true;
document.body.appendChild(script);
}
Appending to head:
function loadScript() {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://www.mydomain/myscript.js';
script.async = true;
head.appendChild(script);
}
Usually when you include some scripts, browser will load them synchronously, step by step.
But if you set
script.async = true;
script will load asynchronously and other scripts will not waiting for them. To fix this problem you can remove this option.
There is an onload event on the script. Use that.
<!doctype html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var script = document.createElement('script');
script.type = "text/javascript";
script.src = "http://code.jquery.com/jquery-2.1.1.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
script.onload = function() {
$('#testing').html('<p>This is a paragraph!</p>');
};
};
</script>
</head>
<body>
<div id="testing"></div>
</body>
</html>
Check your browsers js console. You will probably see something like $ is undefined and not a function. It is because you are running the code in
You can try to wrap the jquery code you want to run in the readyStateChange event of the script tag. Or you can use require.js.
There is a working demo http://jsbin.com/lepapu/2/edit (Click "Run with JS")
<script>
if(!window.jQuery)
{document.write('<script src=http://code.jquery.com/jquery-2.1.1.min.js><\/script>')}
</script>
<script>
$(document).ready(function(){
$('body').html('<p>This is a paragraph!</p>');
});
</script>
The order of scripts matters.

Adding jQuery by demand and use $?

I have a TextBox and a Button:
If the value inside the Textbox is 1 (just emulating a condition)) I need to load jQuery on the fly and use a document Ready function :
I tried this :
function work() //when button click
{
if (document.getElementById('tb').value == '1')
{
if (typeof jQuery == 'undefined')
{
var script = document.createElement('script');
script.src = "http://code.jquery.com/jquery-git2.js";
document.getElementsByTagName('head')[0].appendChild(script);
$(document).ready(function ()
{
alert('');
});
}
}
}
But it says :
Uncaught ReferenceError: $ is not defined
I assume it's because the line : $(document).ready(function ()....
But I don't understand why there is a problem , since i'm, loading jQuery BEFORE I use $...
Question :
How can I fix my code to work as desired ?
JSBIN
You are missing the script onload handler:
var script = document.createElement('script');
// do something with script
// onload handler
script.onload = function () {
// script was loaded, you can use it!
};
Your function becomes:
function work() {
if (document.getElementById('tb').value != '1') { return; }
if (typeof jQuery != 'undefined') { return; }
// jQuery is undefined, we will load it
var script = document.createElement('script');
script.src = "http://code.jquery.com/jquery-git2.js";
document.getElementsByTagName('head')[0].appendChild(script);
// load handler
script.onload = function () {
// jQuery was just loaded!
$(document).ready(function () {
alert('');
});
};
}
Also, do not forget script.onreadystatechange for IE compatibility.
script.onreadystatechange = function () {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
// script was loaded
}
}
Also seems that YepNope would be a good option, too.
JSBIN DEMO
Using YepNope would probably a good option in this case.
yepnope([
{
test: window.jQuery,
nope: 'path/url-to-jquery.js',
complete: function() {
$(document).ready(function() {
//whatever you need jquery for
});
}
}
]);
You can just put that in the head of your document, and it will only load jquery if window.jQuery isn't defined. It's much more reliable (and simpler) than script.onload or script.onreadystatechange. the callback complete will only be called once jquery is loaded, so you can be sure that $ will be defined at that point.
Note: if you're using Modernizr.js on your site, there's a good chance yepnope is already bundled into that script.

Conditional loading of jQuery

I am testing with pure JavaScript if browser seems to support HTML5 and if so, I want to load jQuery and then process the rest of page. If not, some redirection will occur.
<script type="text/javascript">
var canvas = document.createElement('canvas');
if (canvas && canvas.getContext && canvas.getContext('2d')) {
var s = document.getElementsByTagName('script')[0];
var jq = document.createElement('script');
jq.type = 'text/javascript';
jq.src = 'js/jquery.js';
s.parentNode.insertBefore(jq, s);
}
else {
// ... redirection ...
}
</script>
<script type="text/javascript">
$(function () {
//...
}
</script>
But the code above is not working properly, because I got error
Uncaught ReferenceError: $ is not defined
which is clearly saying that jQuery library has not been loaded.
Why? What is wrong with conditional script loading in my code above?
This is a case where it may make sense to use document.write(). You'd need to put this code in the <body> instead of the <head>:
<script type="text/javascript">
var canvas = document.createElement('canvas');
if (canvas && canvas.getContext && canvas.getContext('2d')) {
document.write( '<script src="js/jquery.js"><\/script>' );
}
else {
// ... redirection ...
}
</script>
<script type="text/javascript">
$(function () {
//...
}
</script>
Or, you may be able to use an ordinary <script> tag to load jQuery, but put it after your conditional redirection:
<script>
var canvas = document.createElement('canvas');
if( !( canvas && canvas.getContext && canvas.getContext('2d') ) ) {
// ... redirection ...
}
</script>
<script src="js/jquery.js"></script>
<script>
$(function () {
//...
}
</script>
With either of these approaches, the order of execution is:
The first <script>.
The loading of jquery.js, whether done with document.write() or a simple <script> tag.
The final script.
When you insert a script tag like you are, it will be loaded in the background, not immediately and thus your next script will run before jQuery is loaded. You will need to attach a listener such that you know when jQuery is successfully loaded and you can then run your scripts that use jQuery.
Here's an article that describes how to know when a dynamically loaded script is loaded: http://software.intel.com/en-us/blogs/2010/05/22/dynamically-load-javascript-with-load-completion-notification.
FYI, in your specific case, you also could just have a static script tag that loads jQuery, but place your script that detects whether to redirect or not BEFORE the jQuery script tag. That would be the simplest option.
<script type="text/javascript">
var canvas = document.createElement('canvas');
if (!canvas || !canvas.getContext || !canvas.getContext('2d')) {
// redirect here or whatever
}
</script>
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript">
$(function () {
//...
}
</script>
finally working like a charm, I'm relieved myself !
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script type="text/javascript">
window.onload = function(){
var jqu = "$(console.log('worked'));";
var canvas = document.createElement('canvas');
if (canvas && canvas.getContext && canvas.getContext('2d')) {
var s = document.getElementsByTagName('head')[0];
var jq = document.createElement('script');
jq.setAttribute('type','text/javascript');
jq.innerHTML = jqu;
var jqLoad = document.createElement('script');
jqLoad.setAttribute('type','text/javascript');
jqLoad.setAttribute('src','jquery-1.10.0.js');
jqLoad.setAttribute('id','jqloader');
s.appendChild(jqLoad);
document.getElementById('jqloader').onload = function(){
console.log('loaded');
s.appendChild(jq);
}
}
else {
// ... redirection ...
}
console.log(document);
}
</script>
</head>
<body>
</body>
</html>
jsbin Demo
explanation :
1- using dom functions to append or insert elements are always the best (dynamic and safer more than anything else), and document.write is not recommended over that.
2- at parse-time, whatever functions you have in your script will be evaluated thus you will get an error if you have the script and not loaded the library yet.
3- loading the library and executing the relevant script in the same tag is not recommended. better do the script in another tag (after loading is done completely) to ensure it will work.
4- events for document.onload ensures that the document is loaded and the doms exist so you can append children to them. as for the document.getElementById('jqloader').onload it was just to insure that the jquery library is loaded completely and added to the document, and only then the script will be added after and evaluated.
As others have said, the reason you're getting an error is because you've loaded jQuery asynchronously and it hasn't loaded yet.
There are two ways to accomplish what you want.
You can poll for window.jQuery, or you can use an asynchronous loader callback.
Since you only load jQuery only when you detect canvas support, you won't have to worry about supporting old browsers.
var async_script_load = function (s, callback) {
var script;
script = document.createElement("script");
script.async = "async";
if (s.scriptCharset) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function () {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if (head && script.parentNode) {
head.removeChild(script);
}
// Dereference the script
script = undefined;
callback(200, "success");
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore(script, head.firstChild);
};
async_loader({url:'http://tempuri.org/jquery.min.js'},function() {
//call jquery here.
});
For a polling method, it's as simple as:
var checkJq = function() {
if(window.jQuery) {
//do jQuery
} else {
setTimeout(checkJq,100);
}
}
setTimeout(checkJq,100);

load jQuery in another js file

I have a JavaScript file, which also uses jQuery in it too. To load it, I wrote this code:
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js');
alert("1");
$(document).read(function(){});
alert("2");
This fires alert("1"), but the second alert doesn't work. When I inspect elements, I see an error which says that $ in not defined.
How should I solve this problem?
You need to execute any jQuery specific code only once the script is loaded which obviously might happen at a much later point in time after appending it to the head section:
function include(filename, onload) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
script.onload = script.onreadystatechange = function() {
if (script.readyState) {
if (script.readyState === 'complete' || script.readyState === 'loaded') {
script.onreadystatechange = null;
onload();
}
}
else {
onload();
}
};
head.appendChild(script);
}
include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() {
$(document).ready(function() {
alert('the DOM is ready');
});
});
And here's a live demo.
You may also take a look at script loaders such as yepnope or RequireJS which make this task easier.
The problem here is probably that, even though you include the script, it doesn't mean it is loaded when you try to do $(document).ready(function(){});. You could look into Google Loader to prevent this problem http://code.google.com/intl/fr-FR/apis/loader/

Categories