I have a page that renders HTML blocks from another page on the same domain using IDs. My current code:
<div id=”testdiv”></div>
<script>
jQuery(document).ready(function(){
jQuery('#testdiv').load('/references/embed1.html #testdiv2');
});
</script>
While this loads the content correctly, there is a visible lag between the page loading and the jQuery content loading; depending on the DIV contents it sometimes a full second to display then it just pops into place. This is obviously due to the page not attempting to retrieve the HTML content until DOM Ready so I removed the ready function but the Load function doesn’t run. If I use an iFrame instead it appears to load as the browser executes the code but I lose the ability to only include specific DIV IDs and it’s difficult to make it responsive. Looked at $.ajax but apparently Load uses .ajax so it doesn’t look like there will be a difference.
Simply put – how do I load specific DIV ids from another page without waiting for DOM Ready whether jQuery, JavaScript, iFrames or other method? Second question
Thanks
document readywill be triggered until the whole page were loaded, just remove it and .load() will be invoked after #testdiv had finish render on DOM.
here's the example
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<div id="testdiv"></div>
<div id="error"></div>
<script>
$( "#testdiv" ).load( "/references/embed1.html #testdiv2", function( response, status, xhr ) {
alert("Triggered");
if ( status == "error" ) {
var msg = "Err trying to load ";
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
</script>
https://jsfiddle.net/Angel_xMu/rer3yuny/1/
Ajax is not instant, and nothing you do will change that. Therefore, there will always be some form of delay. You can reduce the delay by removing the need for $(document).ready(), however I suspect it still won't be enough to have it do what you were hoping for.
$.get('page.html', function (result) {
// note, you may need to use `.filter` rather than `.find` depending on the structure of `result`
$('#target').html($($.parseHTML(result)).find('#target2'));
});
or leave your code as is minus $(document).ready and move it to after the target div just like in your example.
The only way to completely remove the delay would be to remove the need for using $.ajax by inserting the html directly into the page server-side.
Related
I have a main.html in which I am trying to load another HTML.
The code in main.html is like this:
<script type="text/javascript">
$(window).load(function(){
$("#divid").load("sample.html");
});
</script>
Inside the sample.html, I have another JavaScript which doesn't work as expected.
<!-- inside sample.html -->
<script type="text/javascript">
... Some JavaScript here ...
</script>
I do not even get the width of an element correctly. Surprisingly, if I put a breakpoint in the JavaScript or put an alert, all seem to work well. This made me guess that page might not be loaded when script runs and by putting alert or breakpoint gives it a bit more time ? I did some searching on web and think that the loading is not in sync which means that the script inside the sample.html page is executing before the page could load. This is just my guess.
I have tried adding JQuery functions ready and load inside the sample.html as well but nothing changes.
Any idea what could be wrong here ?
Use the callback...
this is an example from the doku
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
http://api.jquery.com/load/
and also use jQuery's
$( document ).ready(function() {
console.log( "ready!" );
});
Document ready fires the callback, when the dom is ready. And load fires the callback when the file is loaded.
//EDIT
Please use document ready... here are more details... and also do not load files directly from the file system
$(document).ready(function(){
// You will enter here, wenn the DOM is loaded and ready to use
//When everything is ready to roll you want to load your html file
$("#divid").load("sample.html",function(){
// You will enter this method when sample.html is loaded
// Make sure there is also a div with the id=divid
// to get details on why this is not loading you can also use the
// function signature
// $("#divid").load("sample.html",function(responseText, textStatus, jqXHR){});
// You should also be aware of loading a file from file system can cause to ajax
// errors if it is not served by an http server. Because you can't access local
// files from within JavaScript (security thing)
});
}
I have (basically) this code -
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#loadDiv").load("mypage.html", function(){ alert($("#someText").text()) });
});
</script>
<div id="loadDiv"></div>
However the alert will display "undefined" since the html has not been rendered into the div yet.
I've seen this question - How to wait for jQuery's load function to render loaded content before executing callback function - and Jake's answer is the best for my situation. On my actual page I have eight of these and with a two second delay there are still some of them running before the html is rendered.
Does anyone have a better suggestion than increasing the delay to silly times?
According to the documentation, the load method already waits for the content to be placed in the element before calling the function:
"If a "complete" callback is provided, it is executed after
post-processing and HTML insertion has been performed."
I have tested this, and it does find the loaded content in the element when the callback function runs.
If it doesn't work in your code, you are trying to do something other than what you have shown in the question.
You should be able to wrap your code in the callback with a setTimeout() with a timeout of 0 (browsers are meant to clamp at 4 microseconds, but not all do).
This will push the code onto the event queue, giving the browser a chance to render before the code is executed.
You can set the html empty(if you don't have other html element in the div while the request is loading).
After the success (the complete event)you load the content (now I don't know if the response is an html or a text, i've done the example following your code).
You can also set a predefinite text if the request fail.
Check also this link for more information jquery\load, but this should be work
$("#loadDiv").load("mypage.html", function(response, status, xhr) {
if (status == "success") {
$("#loadDiv").html("");
}
else if(status == "complete"){
$("#loadDiv").text();
}
});
I have the following script that loads a page into a div and not just the targeted div. This is most evident when going back to my index and my header and footer are jammed into the <div id="contentspace"></div>.
I read on here somewhere that the div needs to be placed in it's own page prior to being displayed. Not sure which method would do that. Is this possible without hashtags Thanks for your help
<script type="text/javascript">
$(function() {
$('#header a').click(function() {
$('#contentspace').empty();
$("#contentspace").load(this.href, function(response){
console.log($('#content', response).html())
event.preventDefault();
});
});
});
</script>
The method .load() can load page fragment, simply by specifying a valid jquery selector next to the url.
$('myelement').load('page.html #content', function() {
...
});
Note that when loading page fragments, jquery will remove any SCRIPT element it might contain.
In you example, you would do:
$("#contentspace").load(this.href + ' #content', function(response){
...
});
Did you read the documentation at all? Take a look at the section titled Loading page fragments in the jQuery API for .load(). Essentially you just pass a selector along with the URL of the page to load as the first argument of the method.
I wanted to load some fragments of external content inside a div, through a menu.
Found "load" and "live", found a tutorial used it = success!
Except, like what's explicit in the documentation, it doesn't load JavaScript.
The thing is, the destination page already loads, inside the header, that same JavaScript, 'cause Wordpress loads it in every page. In this particular page, I'm only using the plugin (nextgen gallery) through the jQuery AJAX call.
So, what I believe is my problem is that I somehow need to alert/reload the JavaScript, right?
And how can I do this?
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function(){
// ajax pagination
jQuery('#naveg a').live('click', function(){ // if not using wp-page-numbers, change this to correct ID
var link = jQuery(this).attr('href');
// #main is the ID of the outer div wrapping your posts
jQuery('#fora').html('<div class="loading"><h2>Loading...</h2></div>');
// #entries is the ID of the inner div wrapping your posts
jQuery('#fora').load(link+' #dentro')
return false;
});
}); // end ready function
</script>
PS: I've substituted "live" with "on" but didn't work either.
I'm not sure if I understand... your load() command is puling in some Javascript that you want executed? I'm not sure if you can do that. But if you just need to call some JS upon load() completion, you can pass it a function like so:
jQuery('#fora').load(link+' #dentro', function() {
console.log("load completed");
// JS code to be executed...
});
If you want to execute Javascript code included in the loaded page (the page you retrieve via .load()), than you have to use the url-parameter without the "suffixed selector expression". See jQuery documentation for (.load()):
Note: When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is however called with a selector expression appended to the
URL, the scripts are stripped out prior to the DOM being updated,
which is why they are never executed. An example of both cases can be
seen below:
Here, any JavaScript loaded into #a as a part of the document will
successfully execute.
$('#a').load('article.html');
However in this case, script blocks in the document being loaded into
#b are stripped out prior to being executed:
$('#b').load('article.html #target');
I think that's your problem (although I have no solution for you, sorry).
Proposal: Maybe you can load the whole page (including the Scripts) and remove (or hide) the parts you don't need?
Cheers.
I would like to refire the styling and processing.js scripts that i linked to in the head so that they display correctly when brought in through an ajax-request. I see where in the ajax request this code needs to be, but i don't know how to tell the code to simply reapply the script. I've seen people using getScript() to do this, but from what i can tell this reloads the script, rather than simply telling it repeat or refire. Do all of the scripts need their own reinitialization? I found the syntax highlighters .highlight() method, but i am yet to get the processing script to load. currently, Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']); does not work. I am using current versions of all libraries. Surprised i haven't been able to find the answer yet, as a lot of people seem to have the same problem. Thanks for your help!
index page:
$(document).ready(function () {
// put all your jQuery here.
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Search for link with REL set to ajax
$('a[rel=ajax]').live("click",function(){
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
//$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('fast');
//reapply styles?
//apply syntax highlighting. this works
SyntaxHighlighter.highlight();
//relaod processing sketch, currently displays nothing
Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']);
}
});
}
This the ajax-loaded content:
<!--ajax'd content-->
<??>
<h2>code</h2>
<pre class="brush: php">
$last_modified = filemtime("header.php");
echo("last modified: ");
echo(date("m.j.y h:ia", $last_modified));
</pre>
<script type="application/processing">
</script>
<canvas data-processing-sources="mysketch.pde" id="processing">
</canvas>
</div>
</body>
</html>
<??>
So, let's analyze what usually happens when you include an (external or internal) Javascript code: It will automatically execute only the code that is available in the global scope. "Good" scripts will only add one command to the global scope which will then execute the initialization code somewhere in a function/method.
All you need to do is view the external Javascript file and find out what is being executed from the global scope. There is no general answer to that ... some scripts use an object and call its init() method ... but that is totally subject to the imagination of the developer.
If you have javascript that needs to trigger, you MUST add this to the head element:
var head = document.head || document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.innerHTML = "your AJAX-obtained js code";
head.appendChild(script);
The same trick goes for CSS. Add a element to the head with your CSS declarations as innerHTML. So: make sure to preprocess your AJAX response and split out the JavaScript and CSS elements, then add those to the document header. It's probably easier to make your response a JSON object along the lines of:
{
html: "<html>string<goes>here</goes></html>",
scripts: ["url1","url2","url2",...],
style: ...
}
and then parsing that JSON for the html (which you use as innerHTML for a new document.createElement("div") or something, and then append wherever it needs appending), the scripts (which you turn into elements for HEAD insertion) and the style declarations (which you turn into elements for HEAD insertion).
(On a functional note, your example AJAX response looks like it has PHP code in it. I have no idea what you're using it for, but that looks like a bad response)
Just incase anyone stumbles upon this:
If you have processing.js already loaded, simply call Processing.reload() in your AJAX success/complete function.
Perhaps you already have an element with id="processing" on your page. In that case $("#processing") will only return the first one. If that is the case, change the id or use a class instead.
The other option, which I don't recommend, is to use $("[id=processing]"). That will return every element on the page with id="processing". But, don't use it. Use unique ids in your page, or switch to using classes, whichever works best for you.