make the div load last using jquery or javascript - javascript

I am trying to make my div on my page to load last, what i mean is after everything is loaded then it must load that div using jquery or javascript ?
here is what i tried
<script type="text/javascript">
$(document).ready(function(){
$.get('url', function(data) {
$('.image').html(data);
});
});
</script>

Don't use $(document).ready() because this event fires probably too early for your intention. Use the window.onload event which fires after the page is fully loaded (including images and other resources)
window.onload = function() {
$.get('url', function(data) {
$('.image').html(data);
});
};

Related

How do I run a jQuery function after jQuery is loaded?

At my website, I am loading jQuery asynchronously.
In order to do that, I must run jQuery functions only after it is really loaded.
I've tried two pure JS ways:
<script src="js/jquery-2.2.2.min.js" async></script>
<script>
window.addEventListener('load', function() {
//stuff
}, true);
</script>
And
window.onload = function() {
//stuff
}
But even so I still get Uncaught TypeError: $(...) is not a function at...
How do I fire jQuery functions after the lib is fully loaded?
You need to add the script only after jQuery library is loaded using script tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// your code should be here
alert(typeof jQuery)
</script>
The document ready handler is using to execute the code only after DOM elements are loaded.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
console.log('Outside document ready handler ' + $('.test').length)
$(document).ready(function() {
console.log('Inside document ready handler ' + $('.test').length)
});
</script>
<div class="test"></div>
UPDATE 1: You can use defer if script is in a file, refer following question: jquery loaded async and ready function not working
UPDATE 2: Or you can bind load event handler to the script tag using addEventListener method.
<script async id="script" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
document.getElementById('script')
.addEventListener('load', function() {
alert(typeof jQuery)
});
</script>
FYI : I don't know why you are doing this, for optimizing the speed of content load it's always better to move the script tags at the end of body which helps to load content first.
You could do something like this:
function checkVariable(){
if ( window.jQuery){
Do your jquery stuff here
}
else{
window.setTimeout("checkVariable();",100);
}
}
checkVariable();
Apologies for the formatting...stuck on my phone right now.
I did not see this method listed, so I thought I would demonstrate using the JavaScript HTML DOM EventListener.
Example #1 Using the jQuery.ready() Method:
<p id="test-jquery">jQuery Not Loaded</p>
<script>
$(document).ready(function() {
var elem = $('#test-jquery');
elem.text('jQuery Is Loaded');
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This method will not work since jQuery has yet to be loaded.
Running the above example will output:
ERROR: {
"message": "ReferenceError: $ is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 13,
"colno": 3
}
Example #2 Using the addEventListener() Method:
<p id="test-jquery">jQuery Not Loaded</p>
<script>
window.addEventListener('DOMContentLoaded', function() {
var elem = $('#test-jquery');
elem.text('jQuery Is Loaded');
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This method will work since we are listening for the Window DOMContentLoaded event.
From Mozilla:
The original target for this event is the Document that has loaded.
You can listen for this event on the Window interface to handle it in
the capture or bubbling phases. For full details on this event please
see the page on the Document: DOMContentLoaded event.
A different event, load, should be used only to detect a fully-loaded
page. It is a common mistake to use load where DOMContentLoaded would
be more appropriate.
You can use this:
<script>
document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
// window loaded, external resources are loaded too...
jQuery(function($) {
// your code here: $("a").css(...)
}
}
});
</script>
I used it when inline jQuery script did not work on safari (Mac and iOS) and this solved the problem.
Use document.ready or load the library in the header. That should work.. Be sure to load in the right folder or in the right link. If you are usying a link to load jquery then be sure to have an internet connection

How to load a jQuery function only after the document finish loading

Strange situation:
I am building a menu bar using jQuery and CSS.
In my JavaScript file, I have an on-ready function like so:
$(document).ready(function(e) {
mark_active_menu();
}
and...
function mark_active_menu() {
var elementWidth = $("nav li").width();
alert(elementWidth);
}
For some reason, even BEFORE all the document finish loading, I'm getting the alert message with an incorrect width. Only when I release the message, the rest of the document loads and I'm getting the right width as it should be.
Why my function is being called BEFORE all the document finish loading?
Is there a way to load the function only AFTER a certain element done loading (Example: the nav element)?
You can use window.load, it will be triggered after all the resource have completed loading.
$(window).load(function(e) {
mark_active_menu();
});
The load event fires at the end of the document loading process. At
this point, all of the objects in the document are in the DOM, and all
the images and sub-frames have finished loading, Reference
All the current solutions are just treating symptoms of the main problem. If you want your handler to execute after all your ajax loads, then you may use a promise.
var ajax1 = $.ajax();
var ajax2 = $.ajax();
jQuery(function($) {
$.when.apply($, [ajax1, ajax2]).done(function() {
// your code here
});
});
Try on the window load event :
$(window).load(function() {
//Stuff here
});
To be sure, Try window load
$(window).load(function(e) {
mark_active_menu();
}
Before(sometimes, doesn't load absolutely at the beginning, a few milliseconds after(0-200ms about)):
$(document).ready(function(){
$('body').hide(0);
});
After:
$(window).load(function(){
$('body').delay(500).show(0);
});
In my situation of work with AJAX and HTML. I have the same problem with functions $(document).ready() and $(window).load(). I solved this problem by adding handler of my event (that should work at HTML DOC), to the jQuery function that runs right after AJAX reguest was finished. Read this: "
jQuery.post()" (third parameter in the function).
In my code it looks like this:
var RequestRootFolderContent = function(){
$.post(
'PHP/IncludeFiles/FolderContent.inc.php',
function(data){
$('[class~="folder-content"]').html(data);
//Here what you need
$('[class~="file"]').dblclick(function(){
alert("Double click");
});
}
)
}

Reload javascript file after an AJAX request

After the request, the new elements created are not recognized by the event handlers in my jQuery code.
Is there a way to reload the file to re-register these events?
I'm assuming that you mean that events you've registered for elements that have been replaced by with the results of your ajax requests aren't firing?
Use .live() (see http://api.jquery.com/live/) to register the events against elements that the match the selector (including the new DOM elements created from the results of the ajax), rather than the results of the selector when the event handlers were first, which will be destroyed when they are replaced.
e.g.
replace
$('div.someClass').click(function(e){
//do stuff
});
with
$('div.someClass').live('click', function(e){
//do stuff
});
Important:
While I've recommended using .live() this is for clarity as its syntax is similar to .bind(), you should use .on() if possible. See links in #jbabey's comment for important information.
This question was about binding event handler on DOM element created after the loading of the page. For instance, if after a request ajax you create a new <div> bloc and want to catch the onClick event.
//This will work for element that are present at the page loading
$('div.someClass').click(function(e){
//do stuff
});
// This will work for dynamically created element but is deprecated since jquery 1.7
$('div.someClass').live('click', function(e){
//do stuff
});
// This will work for dynamically created element
$('body').on('click', 'div.someClass', function(e){
//do stuff
});
You would find the documentation here: http://api.jquery.com/on/
This codes works perfect for me..
$("head script").each(function(){
var oldScript = this.getAttribute("src");
$(this).remove();
var newScript;
newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = oldScript;
document.getElementsByTagName("head")[0].appendChild(newScript);
});
It removes the old script tag and make a new one with the same src (reloading it).
To increase the website performance and reduce the total file’s size return, you may consider to load JavaSript (.js) file when it’s required. In jQuery, you can use the $.getScript function to load a JavaScript file at runtime or on demand.
For example,
$("#load").click(function(){
$.getScript('helloworld.js', function() {
$("#content").html('Javascript is loaded successful!');
});
});
when a button with an Id of “load” is clicked, it will load the “helloworld.js” JavaScript file dynamically.
Try it yourself
In this example, when you clicked on the load button, it will load the “js-example/helloworld.js” at runtime, which contains a “sayhello()” function.
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
</head>
<body>
<h1>Load Javascript dynamically with jQuery</h1>
<div id="content"></div>
<br/>
<button id="load">Load JavaScript</button>
<button id="sayHello">Say Hello</button>
<script type="text/javascript">
$("#load").click(function(){
$.getScript('js-example/helloworld.js', function() {
$("#content").html('
Javascript is loaded successful! sayHello() function is loaded!
');
});
});
$("#sayHello").click(function(){
sayHello();
});
</script>
</body>
</html>
In your request callback, call a function that acts on your newly appended or created blocks.
$.ajax({
success: function(data) {
$('body').append(data);
//do your javascript here to act on new blocks
}
});
simple way to solve this problem
$(document).ready(function(){
$('body').on('click','.someClass',function(){
//do your javascript here..
});
});
You can also attach the click handlers to the body so that they never get destroyed in the first place.
$('body').on('click', 'a', function(event) {
event.preventDefault();
event.stopPropagation();
// some stuff
})
var scripts = document.getElementsByTagName("script");
for (var i=0;i<scripts.length;i++) {
if (scripts[i].src)
if(scripts[i].src.indexOf('nameofyourfile') > -1 )
var yourfile = scripts[i].src;
}
jQuery.get(yourfile, function(data){
if(data){
try {
eval(data);
} catch (e) {
alert(e.message);
}
}
});
You can try loadscript plugin for loading the javascript file.
forexample
$("#load").click(function(){
$.loadScript('path/example.js');
});
or
$.ajax({
success: function(data) {
$.loadScript('path/example.js');
}
});
http://marcbuils.github.io/jquery.loadscript/
What do you mean not recognized by jQuery?
jQuery walks the DOM each time you make a request, so they should be visible. Attached events however will NOT be.
What isn't visible exactly?
P.S.: Reloading JavaScript is possible, but highly discouraged!

Jquery manage local script with full ajax site

Basically my app work like that :
Index.php manage call to other pages.
Each page contains 2 function onLoad() and onClose() which are redefined in each page
Index.php call the pages and execute the onLoad
Basically, i preload the page in a hidden div, i execute the predefined $.onLoad function and the i put the loaded content into a visible div
My question is only about the onLoad() scope, i want to remove code from the jquery eval seq when i change page, but i need a way to define it in the page.php file without knowing the container
The eval/seq is probably the eval queue of jquery, can't found info about that, just obtain with firebug...
In 2 words, i would like to be able to remove injected dom and script when i change context (pages)
index.php
$.onLoad = function() {}
$("#blabla").onChange(function() {
$("#data_iframe").load(chaineUrl, {}, function(responseText, textStatus, XMLHttpRequest) {
$("#data_iframe").ready(function() {
$("#data_div").children().remove();
$.onLoad();
$("#data_iframe").children().hide().appendTo($("#data_div")).show(); $("#data_iframe").children().remove();
$.onLoad = undefined;
}
});
});
page.php
<script>
$.onClose = (function(){
$('#container').blablabla();
//alert("test");
});
$.onLoad = (function(){
$('#container').blablabla();
}
</script>
The problem is that the jquery EVAL/SEQ keep growing each time a page is opened
and there are some side-effect like calling multiple time a function...
I guess its a scope problem so can you help me correct my code
(i've try with or without the $ but doesn't change anything)
just for information
<div id="data_div"></div>
<div id="data_iframe"></div>
Thanks
I usually use $(document).ready instead of onload. No need to do the "onload" trigger in load complete function. The ready function within the page.php will do the same job.
And how about direct load into data_div?
index.php
$("#blabla").onChange(function() {
$("#data_div").load(page.php);
});
page.php
<script>
$(document).ready(function() {
$('#container').blablabla();
});
</script>
I didn't try page close function before, may be it is not what you want. But you can try:
<script>
$(document).ready(function() {
$('#container').blablabla();
$(window).unbind('unload');
$(window).unload(function(){
$('#container').blablabla();
//alert("test");
})
});
</script>

Loading an external script after page load with jQuery

I'm a little confused how to do this, basically I have a page that has a Facebook Share button inserted via JavaScript:
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>
The problem is that it's blocking the page load at that part, how can I insert this tag after page load and still have the script execute? I'll like to do it in an unobtrusive way, ideas?
Use the jQuery getScript command inside $(document).ready. This will download the script after the page has loaded. Example:
$(document).ready(function() {
$.getScript("http://static.ak.fbcdn.net/connect.php/js/FB.Share", function() {
alert("Script loaded and executed.");
});
});
You could use the jquery.getScripts to load it asynchronously.
Try something like this:
$(document).ready(function() {
var script = document.createElement( 'script' );
script.src = "http://static.ak.fbcdn.net/connect.php/js/FB.Share";
script.onload=optionallyDoSomethingWithTheScriptYouJustLoaded();//not needed
var headID = document.getElementsByTagName("head")[0];
headID.appendChild(script);
});
Inject the script tag into the dom as a callback of the document ready event.
you could do something like:
$(function() {
$.getScript('http://static.ak.fbcdn.net/connect.php/js/FB.Share', function() {
//do nothing here
});
});

Categories

Resources