JQuery maximum .load calls? - javascript

I am using the LiquidSlider framework and in each tab there is lots of HTML. So I decided to put the HTML into separate .html files to make the main page index.html cleaner.
Here is my HTML:
..
<head>
.. <-- Import jquery, slider files, etc -->
<!-- Import HTML from other files into divs -->
<script>
$(function(){
$("#about-content").load("about.html");
$("#other-content").load("other.html");
$("#help-content").load("help.html");
$("#contact-content").load("contact.html");
});
</script>
</head>
<body>
<section id="navigation">
..
</section>
<div class="liquid-slider" id="main-slider">
<!-- About -->
<div>
<h2 class="title">about</h2>
<div id="about-content"></div>
</div>
<!-- Other -->
<div>
<h2 class="title">other</h2>
<div id="other-content"></div>
</div>
<!-- Help -->
<div>
<h2 class="title">help</h2>
<div id="help-content"></div>
</div>
<!-- Contact -->
<div>
<h2 class="title">contact</h2>
<div id="contact-content"></div>
</div>
</div>
<section id="footer">
..
</section>
</body>
..
So when the document is loaded, theoretically the HTML would be loaded in via the .load calls right? It seems to work fine, until it gets to the very last tab (contact), where it just fails to load any content..
Odd right? I tried moving the divs around to see if it was a problem with my html files, but the last element always fails to load. Then I tried adding another tab, and the last two fail to load. This leads me to believe there is an upper-limit to the number of .load calls, capped at 3?
Anyone have any ideas or see any obvious problems? Or even suggest any better ways of achieving the same thing?
Thanks.

RTM, there's nothing there about a max number of calls, but there's a lot of information (and examples) of what kinds of callbacks you can use, which might just help you to diagnose the problem itself, for example:
$("#contact-content").load("contact.html", function( response, status, xhr )
{
if ( status == "error" )
{
var msg = "Sorry but there was an error: ";
console.log(xhr);//<-- check this
$( "#error" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
As an alternative, just go for the old-school $.get call, since you don't seem to be passing any data to the server:
$.get( "contact.html", function( data )
{
$("#contact-content").html(data);
});
Another thing to consider might be: given that you're using liquidSlider, I take it not all of the content is visible from the off. Why not register a click handler, that .load's that content when the user actually clicks something? That does away with that series of load calls... Perhaps it's a concurrency issue of sorts. By that I mean: browsers restrict the number of concurrent AJAX requests that can be made.Perhaps you're running into that restriction, and have to wait for the requests to be completed? It's a long shot, but you never know... If you want to, check your browser here
But either way, using JS to fetch parts of the content dynamically is all well and good, but remember that I can switch off JS support in my browser. Or that, if your JS contains a syntax error, the script execution grinds to a halt, leaving me with a (half) empty page to gaze at.
Just using any server-side scripting language seems to me to be a better fit:
//index.php -- using PHP as an example
<div id="contact-content"><?php include 'contact.html'; ?></div>
After this gets processed by PHP, the response from the server will be a fully-fledged html page, that doesn't require any JS-on-the-fly loading. It'll almost certainly perform better, and still allows for cleaner html code on your server...

Server Side Includes would seem to me to be a better way of achieving the same thing. Use the right tool for the right job and all that.

<script>
var array = ['about', 'other', 'contact', 'help'];
for (i in array)
{
$('#'+array[i]).load(array[i]+'.html', function(){ });
}
</script>

Related

Loading different pages while keeping the same header

I have a question, I'm working on my first portfolio with html, css and javascript.It's just a simple site with a header with the nav menu and the body with some of my info, I was wondering if there's a way besides iframe to load only the body everytime I click a link without affecting the header:
<header>
<nav>
Home, about me, etc
</nav>
</header>
<body>
this is my home page
</body>
To really get in to one page app development using a library like Angularjs really does the trick. If you just need something really simple you can use the jQuery load function. For instance:
<body>
<button id="home">Home</button>
<button id="about">About</button>
<button id="examples">Examples</button>
<div id="content">
this is my home page
</div>
</body>
<script language="Javascript">
$("#home").click(function() {
$( "#content" ).load( "home.html" ); //Load all retrieved content
});
$("#about").click(function() {
//Only load content from a specific node
$( "#content" ).load( "about.html #desc" );
});
$("#examples").click(function() {
//More specific loading of node
$( "#content" ).load( "examples.html #storeMain .container" );
});
</script>
This is the same question that started me off learning to program.
Things have gotten a lot better as far as loading dynamic content on the fly... but also - much more complicated as far as setup / build tools / JS frameworks etc.
People will say --- just use HTML or PHP / and that it doesn't matter if the whole page is reloaded and the header repaints... but those people aren't like you. What if you want to look at a picture of the band WHILE listening to a song (myspace)... - or you want your header to fade to a different background and do an animation...
Here is a PHP example that explains it all: https://css-tricks.com/dynamic-page-replacing-content
Here is a hacky JS way to do it / where all of the info is on one page... but is hidden and then shown with JS / but - the URL isn't going to change: https://codepen.io/sheriffderek/pen/zxmjgr
// build a reusable function that switches the "view"
var switchView = function(trigger) {
$('.view').addClass('hidden');
var currentSection;
currentSection = $(trigger).data('view');
$('.' + currentSection).removeClass('hidden');
console.log("you are currently on:" + currentSection);
};
// when you click the menu item... run that function to switch to the associated "view" based on it's data attribute
$('.view-controls a').on('click', function() {
switchView(this);
});
$('.header').on('click', function() {
$('.compact-menu').toggleClass('active');
});
$('.compact-menu a').on('click', function() {
$('.compact-menu').removeClass('active');
}); // I had to add this code just to post a codepen link : /
Example in action: http://bryanleebrowncomposer.com
Not ideal... but if you aren't going to have URL change anyway... this is actually better for SEO - and it's easy - and gets you the snappy style.
Here is a JavaScript framework way: https://www.codementor.io/sheriffderek/less-than-ambitious-websites-with-ember-js-5mtthoijp
I love Ember.js - but if you were going to try your hand at another framework - I'd take a look at this vue.js way: https://scotch.io/tutorials/how-to-build-a-simple-single-page-application-using-vue-2-part-1
All roads lead to pain and suffering - for the most part. Good luck! Post your outcome, will yah?
You could dynamically load your pages and inject it to your main page (single page).
As another option, which is partially not what you are looking for, you can load different pages via url and then dynamically rendering a header/footer onload (multiple page). But multiple pages will allow you to avoid having to manipulate URL states manually through something like domain.com?page=about and it's generally much more manageable in terms of regular website development.
If I make it single page, I load the body content via ajax. Like so
<div class="header">Lorem ipsum</div>
<div class="content-wrapper">
<!--Load content HTML here via ajax -->
</div>
<div class="footer">Lorem ipsum</div>
For multi-page setups, I do this
<div class="header-wrapper">
<!--Load header HTML here via ajax or render them via a javascript component -->
</div>
<div class="content-wrapper">Lorem ipsum</div>
<div class="footer-wrapper">
<!--Load footer HTML here via ajax or render them via a javascript component -->
</div>
The ajax part is as simple as this. (using jQuery ajax, axios, or http)
$.ajax({
type : 'GET',
url : 'foo.html',
dataType : 'html',
success : function(data){
wrapper.innerHTML = data;
},
Look up dynamically loading html via ajax so that you don't have to constantly repeat yourself implementing the same headers/footers across your pages. OR, like I said, you can also make/adopt a UI component to do it for you without ajax.

Using JavaScript to load external HTML

I want to keep the code short and clean. So I'm importing tons of HTML files.
I have this in head:
<script>
var loadHtml(file) {
$("#LoadHTML").load("html/file.html");
});
</script>
And this in body:
<div id="LoadHTML"></div>
The problem is I have to duplicate the script for each <div> I have.
Is there a way I can make a placeholder in the script and do what I have visualized?
<!-- Head -->
<script>
$(function(){
$("#LoadHTML").load("html/{data}.html");
});
</script>
<!-- Body -->
<div id="LoadHTML" data="file"></div>
How do I do it so I only have to use the script once?
You could group the elements to be loaded by a common class and use a data attribute to set the URL to target the AJAX request to, something like this:
$(".load").each(function() {
$(this).load($(this).data('target'));
});
<div class="load" data-target="html/file.html"></div>
<div class="load" data-target="html/foo.html"></div>
<div class="load" data-target="html/bar.html"></div>
With that being said, I would strongly suggest you use server side includes where possible instead of your current approach. Using client side requests as you are will make many more, potentially needless, requests to your server, and hence slowing it down.
Yes you can!
$("#LoadHTML").load("html/" + data + ".html");
where data is keyword of your template.
id has to be unique. You may have to generate the id name so it would be #LoadHTML1, #LoadHTML2, #LoadHTML3, etc.
Alternatively use class so it's ".LoadHTML"

Blocking UI on document ready

I'm working on a web application which needs to be compatible with Internet Explorer 8 (you know, compatible with the HELL). The thing is that I´m uploading a file which later is processed by a PHP code and refresh the page. When I have a processed file I used that file to insert data into a table, so I need a processbar and block UI while I insert this data (I need to call another PHP process for each row)
The problem is the next one, I want to block that UI, I have the logic and all compatibility problems solved; but after 5 days of work, I can´t block UI. This is a minimum code (which encapsulate all we need) in order to simplify the idea:
$(document).ready({
(...)
$("#title").html('some text');
$("#bar").html('');
$.blockUI({message: $('#window'),css:{width:'303px'}});
go = true;
while (go){
$.ajax({<ASYNC FALSE AJAX CALL});
if (!file.lines) go = false;
<update progress>
}
$.unblockUI();
(...)
});
Obviously, the $.blockUI should block main thread (until I unblocks) and show a personalized window, which have the next code is:
<div id="window" style="display: none; cursor: default">
<div id="title_bar">
<div id="titulos">some text</div>
<div id="cerrar"></div>
</div>
<div id="body">
<img src="an icon"
alt="enviando" border="0" width="33" height="33" id="enviar">
<p class="titulo" id='title'></p>
<p class="texto" id='bar'></p>
<br />
</div>
</div>
I think the problem is that I´m executing that block on a thread which is not main thread, and i cant really blocks UI; but I need that block because I have to force the user to wait until I process all of the information.
Thank guys, I hope you could help me with this.
I think mostly because of synchronous, but if you make it async you need make the changes in your code. Remove while-loop and invoke a function, that will make an async call and on successful completion invoke the same function recursively. Once your terminal condition is met, unblock the UI as below:
$.blockUI({message: $('#window'),css:{width:'303px'}});
// based on the above code I assume you will get file as a response.
process();
function process(file){
if (file && !file.lines){
$.unblockUI();
}
$.ajax({<ASYNC TRUE AJAX CALL})
.done(function(file){
<update progress>
process(file);
});
}

template insertion in a editor

Describing a scenario:
I am going through the code mentioned below.B asically I am trying to figure out how to program so that
when a user clicks on "Use Template" button , it gets inserted into an editor.
Page 1:
There are lot of templates present
When a user clicks on the "Use Template" button on , it gets inserted into an editor that is present in
the next page (Page 2).
Please find the code snippet below for the first two templates I am going through:
<div id="templatesWrap">
<div class="template" data-templatelocation="templateone" data-templatename="Template ONE" data-templateid="" >
<div class="templateContainer">
<span>
<a href="https://app.abc.com/pqr/core/compose/message/create?token=c1564e8e3cd11bc4t546b587jan31&sMessageTemplateId=templateone&sHubId=&goalComplete=200" title="Use Template">
<img class="thumbnail" src="templatefiles/thumbnail_010.jpg" alt="templateone">
</a>
</span>
<div class="templateName">Template ONE</div>
<p>
Use Template
</p>
</div>
</div>
<div class="template" data-templatelocation="templatetwo" data-templatename="Template TWO" data-templateid="" >
<div class="templateContainer">
<span>
<a href="https://app.abc.com/pqr/core/compose/message/create?token=c1564e8e3cd11bc4t546b587jan31&sMessageTemplateId=templatetwo&sHubId=&goalComplete=200" title="Use Template">
<img class="thumbnail" src="templatefiles/thumbnail_011.jpg" alt="templatetwo">
</a>
</span>
<div class="templateName">Template TWO</div>
<p>
Use Template
</p>
</div>
</div>
And so on ....
How does the link "https://app.abc.com/pqr/core/compose/message/create?token=c1564e8e3cd11bc4t546b587jan31&sMessageTemplateId=templatetwo&sHubId=&goalComplete=200" is inserting the template into the editor which is located on the next page? I haven't understood the token part and lot's of ID's present in the link
which I think are thereason behind inserting the template.
Has anyone come across such link before? Please advise.
Thanks
MORE CLARIFICATIONS:
Thanks for your answer.It did help me somewhat. I have few more questions:
Basically, I am using TinyMCE 4.0.8 version as my editor. The templates, I am using are from here:
https://github.com/mailchimp/email-blueprints/blob/master/templates/2col-1-2-leftsidebar.html
Some questions based on "Tivie" answer.
1) As you can see in the code for "2col-1-2-leftsidebar.html " it's not defined inside <div> tags unlike you defined it in <div> tags. Do you think that I can still
use it using "2col-1-2-leftsidebar.html " name?
2)I believe,for explanation purpose, you have included
`"<div contenteditable="true" id="myEditor">replaced stuff</div>`
and
<button id="btn">Load TPL</button>
<script>
$("#btn").click(function() {
$("#myEditor").load("template.html");
});
</script>
in the same page. Am I right? ( I understand you were trying to make an educated guess here, hence
just asking :) )
In my case, I have a separate page, where I have written code for buttons just like you wrote in editor.html like the following:
<button id="btn">Load TPL</button>. My button is defined inside <div class="templateContainer">.
Also, my templates are defined in a separate folder. So, I will have to grab the content(HTML Template), from
that folder and then insert into TinyMCE 4.08 editor. (Looks like two step process). Could you elaborate
on how should I proceed here?
More Question As of Dec 27
I have modifier my code for the template as follows:
<div class="templateName">Template ONE</div>
<p>
Use Template
</p>
Please note, I have added an additional id attribute for the following purpose.
If I go by the answer mentioned in the Tivia's post, is the following correct?
<script>
$("#temp1").click(function() {
$("#sTextBody").load("FolderURL/template.html");
});
</script>
My editor is defined like the following on Page 2 (Editor Page).
<div class="field">
<textarea id="sTextBody" name="sTextBody" style="width:948px; max-width:948px; height: 70%"></textarea>
</div>
I am confused, like, the script tag I have defined is in Page 1 where I have defined all the template related code
and the Page 2(Editor) page is a different page. It's simply taking me to Editor page (Page 2) and hence not working.
Please advise where I am wrong.
Thanks
MORE QUESTIONS AS of Jan 2
The problem Iam facing is as follows. Basically, for first template , I have the following code.
Code Snippet #1 where "Use "Template" button is present:
<div class="templateName">Template ONE</div>
<p>
Use Template
</p>
And the function suggested in the answer is as follows:
Code Snippet #2 where Editor is present:
<script>
$("#temp1").click(function() {
$("#sTextBody").load("FolderURL/template.html");
});
</script>
Since, I believe I first need to reach to that page after user clicks on "Use Template" button, where the editor is located, I have defined Code Snippet #1 on Page 1 and have defined the Code Snippet #2 and <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> as the very first two script tags in the Page 2 ( Editor Page). But still when I click on "User Template" button on Page 1, it's just letting me to next page and not loading the template into the editor.
Am I doing something wrong here? Please advise.
P.S. The problem I feel is somehow the click function on Page 2 is not getting activated with the temp1 id button mentioned on Page 1.
Thanks
Well, one can only guess without having access to the page itself (and it's source code). I can, however, make an educated guess on how it works.
The URL params follows a pattern. First you have a token that is equal in all templates. This probably means the token does not have any relevance to the template mechanism itself. Maybe it's an authentication token or something. Not relevant though.
Then you have the template identification (templateOne, templateTwo, etc...) followed by a HubId that is empty. Lastly you have a goalComplete=200 which might correspond to the HTTP success code 200 (OK).
Based on this, my guess would be that they are probably using AJAX on the background, to fetch those templates from the server. Then, via JScript, those templates are inserted into the editor box itself.
Using JQuery, something like this is trivial. here's an example:
template.html
<div>
<h1>TEST</h1>
<span>This is a template</span>
</div>
editor.html
<!DOCTYPE HTML>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div contenteditable="true" id="myEditor">
replaced stuff
</div>
<button id="btn">Load TPL</button>
<script>
$("#btn").click(function() {
$("#myEditor").load("template.html");
});
</script>
</body>
</html>
Edit:
1) Well, since those templates are quite complex and include CSS, you probably want to keep them separated from you editor page (or the template's CSS will mess up your page's css).
However, since you're using TinyMCE, it comes with a template manager built in, so you probably want to use that. Check this link here http://www.tinymce.com/wiki.php/Configuration:templates for documentation.
2) I think 1 answers your question but, just in case, my method above works for any page in any directory, provided it lives on the same domain. Example:
<script>
$("#btn").click(function() {
$("#myEditor").load("someDirectory/template.html");
});
</script>
I recomend you check this page for the specifics on using TinyMCE http://www.tinymce.com/wiki.php/Configuration:templates
EDIT2:
Let me explain the above code:
$("#btn").click(function() { });
This basically tells the browser to run the code inside the brackets when you click the element with an id="btn"
$("#myEditor").load("someDirectory/template.html");
This is an AJAX request (check the documentation here). It grabs the contents of someDirectory/template.html and places them inside the element whose id="myEditor"

calling an external script and .load jquery conflict

I'm pretty sure this is another DOH! facepalm questions but as designer and not a programmer I need some help getting it right.
What I have is an index file calling local .html files via jQuery .load. Just like this:
(some tabs functionality not relative here - thus the link target call)
Lightbox</li>
<div id=lightbox">
<div class="load">
<script type="text/javascript">
$('.load').load('examples/lightbox.html');
</script>
</div>
</div>
I also have an external .js file that has a bunch of functions that handles some lightboxes among other things. Standard <script src="js/typography.js" type="text/javascript"></script>
Which contains:
$(document).ready(function(){
$(".open-lightbox").on("click", function(){
$('.lightbox').css('display','block');
});
$('.close-lightbox').click(function(){
$('.lightbox').css('display','none');
});
});
My problem is that if the externally called .html file has any elements dependent on the .js file ie. the lightbox popup it doesn't work.
something like :
LightBox Link
<div class="lightbox">
lightbox content
Close
</div>
If i move the html code right to the index page instead of the .load, no problem, same if I moved the JS as an inline <script>...</script> rather than calling it extrenally. Works fine in both cases.
My spidey sense tells me this has something to do with my function and .load not executing in the order I need them to, but my javascript copy/paste skills only go this far.
Can anyone tell me if I can make this combination work? I'd really appreciate it.
EDIT
Maybe I explained my self poorly so let me try and post a better example.
If my index code is as followed everything works: My lightbox pops up as intended.
<li>Link to open Tab Content</li>
<div id="thistabid">
<--Tab Content below-->
<div class="somehtmlpage-load">
LightBox Link
<div class="lightbox">
lightbox content
Close
</div>
</div>
<--End Tab Content-->
</div>
When the said tab is clicked the content inside "thistabid" show up. Whatever that content may be.
Now if i do :
<li>Link to open Tab Content</li>
<div id="thistabid">
<--Tab Content below-->
<div class="somehtmlpage-load">
<script type="text/javascript">
$('.somehtmlpage-load').load('examples/lightbox.html');
</script>
</div>
<--End Tab Content-->
</div>
The lightbox doesn't work. The content of lightbox.html is
LightBox Link
<div class="lightbox">
lightbox content
Close
</div>
Same as the html in the 1st example where everything works. The only difference it's being jQuery loaded rather than hard coded.
What I mean by "if the externally called .html file has any elements dependent on the .js file ie. the lightbox popup" is that if the html is part of the externally called file then the lightbox function isn't working. If it's hard coded it pops up like intended.
On 1st glance the .on seems like should be the solution but most likley my implementation of it is off the mark :/
The 'on' or the 'live' function needs to be applied through an element that exists on the page. Generally some parent of the actual element is used. Can you try something on the following lines with the correct references to the elements on your page:
<li>Link to open Tab Content</li>
<div id="thistabid">
<--Tab Content below-->
<div class="somehtmlpage-load">
<!--leave tab empty for now -->
</div>
<--End Tab Content-->
</div>
<script>
(function(){
$('.somehtmlpage-load').load('examples/lightbox.html');
//live or on needs to be applied to an element that exists on th page
$('#thistabid').on('click', '.open-lightbox', function(){
$('.lightbox').css('display','block');
});
$('#thistabid').on('click', '.close-lightbox', function(){
$('.lightbox').css('display','none');
});
})();
</script>
There seems to be a race condition between your load() and document ready.
To address this you'll need to:
either wait for the load() to complete before you attach the click events
or attach the click to the container of your load() step and use event delegation.
See this page and this other one for more information on how to use on() for delegation.
The code would look like this:
$(".somehtmlpage-load").on("click", ".open-lightbox", function(){
$('.lightbox').css('display','block');
});
Using a SSI solved my problem. I was trying to keep it all Local Drive friendly but it seemed to be causing more problems than anticipated.
Pick your favorite dev environment...I didn't run into any conflicts on either.
ASP - <!--#include file = "examples/lightbox.html" -->
PHP - <?php include 'examples/lightbox.html';?>
Just in case someone else runs into a similar problem.

Categories

Resources