Proper way to handle ajax HTML block - javascript

So I was wondering what is the "spec" or "proper" way to handle HTML that is used via ajax.
For example, should I keep all the HTML in the actual page that is using it? Or should I just an ajax call to load it in?
Is there performance increase in keeping it loaded in the page since its one less load? Or does loading that extra data at page load off-set it.
Here is a screenshot illustrating what I mean.. You can see the {name} which is changed depending on what the user provide (limited characters of course).
Any help/opinion is appreciated! Thanks!
Partial source for those asking:
<!-- text field -->
<div class="add-field-wrapper float-left">
<input type="radio" value="text" name="input_type" id="rad-type-text" class="type-radio-btn">
<label for="rad-type-text" class="radio-lbl" data-tooltip="Used for simple inputs such as: <b>Phone Number</b> or <b>Email Address</b>">
<img src="https://placeholdit.imgix.net/~text?txtsize=16&txt=70x70&w=70&h=70" class="field-type-icon" />
<div class="field-type-text">Text Field</div>
</label>
</div>
<!-- select -->
<div class="add-field-wrapper float-left">
<input type="radio" value="select" name="input_type" id="rad-type-select" class="type-radio-btn">
<label for="rad-type-select" class="radio-lbl" data-tooltip="Use this option when you need to provide a list of choices for the user." >
<img src="https://placeholdit.imgix.net/~text?txtsize=16&txt=70x70&w=70&h=70" class="field-type-icon" />
<div class="field-type-text">Select Menu</div>
</label>
</div>
<!-- textarea -->
<div class="add-field-wrapper float-left">
<input type="radio" value="textarea" name="input_type" id="rad-type-textarea" class="type-radio-btn">
<label for="rad-type-textarea" class="radio-lbl" data-tooltip="The textarea field will appear as a <b>WYSIWIG</b> (What you see is what you get) editor. This allows for some customization of the appearance of the input.">
<img src="https://placeholdit.imgix.net/~text?txtsize=16&txt=70x70&w=70&h=70" class="field-type-icon" />
<div class="field-type-text">Text Area</div>
</label>
</div>
Edit:
<!-- Datepicker HTML block - used in JS -->
<div id="datepicker_html" style="display: none;">
<div id="{name}-block" class="datepicker-wrapper form-input-wrapper">
<div class="template-drag-handle"><img src="images/design/up-down-icon.png" class="template-drag-handle-icon" alt="Drag" /></div>
<div class="inputs-wrapper">
<div class="form-row"><input type="text" name="{name}" class="input-datepicker" placeholder="{placeholder}" id="{name}"/></div>
</div>
<?php echo $default_template_chkbox_options_html; ?>
</div>
</div>
That's a "piece" of the html.. it gets loaded into a JS variable:
This is what processes it -- adds the name, changes the placeholder (these can be reused as many times as you want)
function addDatePickerField(){
//Get the HTML
var datepicker_html = $('#datepicker_html').html();
datepicker_html = datepicker_html.replaceAll(/{name}/g, input_name_underscores);
datepicker_html = datepicker_html.replaceAll('{placeholder}', input_name);
$('#template-fields-wrapper').append(datepicker_html);
wrapUpAddInput('datepicker');
}
I just didnt now it if would be better to do an ajax call, store the "external" html and call it in when I need it -- Like, that datepicker HTML block, would be store in separate file, then on a link, load into the DOM.

I will try to address your question, even though it's a very broad one.
Generally, loading your content (e.g. HTML) dynamically via an ajax request does not always give you a performance boost, it really depends what you are doing and trying to achieve.
Should you always pre-load all of your HTML content with the initial request ? Or should you ajax load a portion of it after the page is already loaded on screen ? that is solely depends on your application and needs.
I will explain by an example:
Assuming I am developing a content site, which will be mainly content oriented (e.g articles) and will be served from traditional web browsers (desktop or mobile) then loading my articles for each page via ajax might not be a good idea, with very few rare exceptions.
On the other hand-
If I am developing a web application that needs to send and receive blocks of data in "real time", a project that contains a rich UI which has to have a rich and "enterprise"-like experience where stuff is being executed, updated and displayed on-the-fly smoothly without having to refresh and re-load my application page every time I am saving my work or executing an operation - I will certainly use ajax requests for handling some of that work.
Another aspect is the overall loading time of your page:
Some web-sites are loading some of their HTML via ajax after the page body is loaded - by doing this they are reducing the perceived loading-time of the page, by "perceived" I mean - to the user, it appears to load faster since the partial page is loading almost instantly, and then some blocks inside of the page are loading async via ajax.
Like i've said, this is a very broad question and there are many methods to learn and investigate to finally see what works best for your specific needs.
Good luck

Related

Upload part of a page or one picture from the page - the first (as soon as possible)

I am using AngularJS 1.4, and this is the code for my page
<div ng-app="myApp">
<div ng-controller="mainController">
<div ng-controller="first"> // this is ng-include - first.html
<img id="bannerImage"/>
</div>
<div ng-controller="first2"> // this is ng-include - first2.html
<img id="bannerImage1"/>
</div>
<div ng-controller="first3"> // this is ng-include - first3.html
<img id="bannerImage2"/>
</div>
<div ng-controller="second"> // this is ng-include - second.html
<img id="mainImage"/>
</div>
</div>
</div>
I need to first load "mainImage.jpg" in "second.html", but judging by the console loads all in the following sequence:
first.html
first2.html
first3.html
second.html
bannerImage.jpg
mainImage.jpg
mainImage2.jpg
mainImage3.jpg as include order in page
I need to load the picture "mainImage,jpg" as soon as possible and display it on the page.
Preferably, the order would be like that or better:
second.html
mainImage.jpg
first.html
...........
That isn't possible without knowing the image urls and preloading them prior to calling them.
In your described scenario, where template pages are being loaded, it doesn't seem like this is an option.
The reason why what you are observing is happening is because the server for your jsp is composing the html. So the html is all composed into the stream writer for the source code. Once the source code is sent to the browser, it then renders the source. It will request the images as they are encountered in the source.
There is no way to mix the image requests with the html composure because they are two separate actions. One is composing a string for a stream writer, and the other is making network requests for external resources.
The only hope if you are trying to change this is to cache the external resources prior to them being requested.
One way to attempt to preload the image would be to save it to a variable in the head of the document using JavaScript
<head>
...other related head elements...
<script>
(function cache(){
var mainCache = new Image();
mainCache.src = "mainImage.jpg";
})()
</script>
This approach will at least start the loading process immediately upon the page starting up, however depending on the image size it may still be loading as the page renders.

Formatting dynamically formed HTML elements created after Script is run

So this is actually a very tricky concept to portray so here is my attempt.
I am utilizing an HTML form template in LANDesk Service Desk - tool is irrelevant but important to note that there is back-end code that I cannot touch that is generating HTML.
So basically, the tool is pulling data from a back-end database containing a list of objects. It then inputs this data into an HTML form template that I have created using variables as placeholders for the objects. The HTML is then built on the fly with however many objects are in the database. Thus, I have no way of accessing the head - (which means native JS, and inline CSS).
My template looks like this...
<div class="my-template">
<a class="my-template my-link">My Link</a>
</div>
<script>
var myLinks = document.getElementsByClassName('my-link');
for (var i = 0 ; i < myLinks.length ; i++) {
myLinks[i].style.display = "none";
}
</script>
When I view the source on the loaded page it looks something like this...
<body>
<!--misc. page stuff-->
<!--First Item-->
<div class="auto-create">
<div class="my-template">
<a class="my-template my-link">My-Link</a>
</div>
</div>
<!--Second Item-->
<div class="auto-create">
<div class="my-template">
<a class="my-template my-link">My-Link</a>
</div>
</div>
</body>
All of the elements are formatted the way I want them to be...besides the last element on each page. I have determined that this is because each time the tool is running the object through the template, it is running the script. The issue is, there is a stupid default button that they place at the bottom of each object that is broken. (This is why I have the script changing the style to display: none..should have mentioned this earlier). Basically I want to delay the execution of the script until not only the object has been run through the template...but the entire page has loaded...but I can't seem to get the last button to go away.
I know that this is a lot of poorly written words trying to form an explanation, but I really think this is impossible...but I am convinced there has to be a way. (Also, the company isn't providing us with any help in finding a workaround, so I had to basically MacGyver this one

How to create an HTML module angular

Learning HTML/Angular.
I have a bunch of HTML code that I want to be re-usable. Basically I write it once and modify the same code base, then just insert the dynamic data using Angular.
My question is - How do I create re-usable HTML code that can be injected into a page using Angular?
For instance, lets say I am an app developer and want to showcase 25 apps on the same page each with their own HTML component (not just a bunch of images). Rather than copying the HTML 25 times I would just like to inject that HTML snippet via some angular command, then insert the text into the corresponding divs etc. I need to stick with Angular/HTML (no other frameworks)
Or is there a better way?
(look at the image for reference - imagine inserting that layout 25 times without duplicating code)
I have tried this using ng-repeat but when I do so it throws the repeating items in the same spot on top of each other. I was hoping that for every div that is repeated it would put it underneath the other div.
<div id="apps" ng-controller="MyApps">
<div id="appsection" ng-repeat="app in applist">
<img class="rightappimg" src={{app.img}} />
<strong class="appbannertext">{{app.firstLine}}</strong>
<strong class="appbannertextsubtitle">{{app.secondLine}}</strong>
<strong class="appbannertextsubtitlesmall"><span class="ios">iOS, iPhone, iPad</span> & <span class="android"> Android</span></strong>
<strong class="appbannerdescriptiontitle">{{app.fourthLine}}</strong>
<p class="appbannerdescription">{{app.fifthLine}}</p>
</div>
</div>
Ok the answer was to us ng-repeat as such:
<div id="apps" ng-controller="MyApps">
<div id="appsection" ng-repeat="app in applist">
<img class="rightappimg" src={{app.img}} />
<strong class="appbannertext">{{app.firstLine}}</strong>
<strong class="appbannertextsubtitle">{{app.secondLine}}</strong>
<strong class="appbannertextsubtitlesmall"><span class="ios">iOS, iPhone, iPad</span> & <span class="android"> Android</span></strong>
<strong class="appbannerdescriptiontitle">{{app.fourthLine}}</strong>
<p class="appbannerdescription">{{app.fifthLine}}</p>
</div>
And then simply to specify a min-height in the div id in the CSS file so the items wouldn't overlap each other.

Change CSS settings of a page before page changing

I'm using Jquery mobile for my mobile application. before I changing a page I want to make some CSS changes on that page. When I am setting for example adding class to id of the next page,or color change: $("#divA1").css("background-color","blue");
It change the same id on the current page (if it exist) and only then change next page. How can I set my CSS settings while on one page but load the next page with those CSS settings.
In most scenarios, jQuery Mobile loads additional pages into the DOM via ajax calls. This is a fairly fundamental part of how it works and you should insure that all markup IDs across all pages are unique.
<div id="page1" data-role="page">
<div data-role="content">
<div id="myContent1"></div>
</div>
</div>
<div id="page2" data-role="page">
<div data-role="content">
<div id="myContent2"></div>
</div>
</div>
If your pages contain similar sub-componants, consider a class instead:
<div id="page1" data-role="page">
<div data-role="content">
<div class="myContent"></div>
</div>
</div>
<div id="page2" data-role="page">
<div data-role="content">
<div class="myContent"></div>
</div>
</div>
Classes allow for selection such as $("#page1.myContent").css("background-color");
If it must be on a new page, you have three options.
You can pass a variable in the URL to test on the new page and change the CSS appropriately. eg. www.url.com?newcolor=f00
You can put a hidden form on the current page, update the values in it and pass it when you go to the next page. (Ugly way to do it but it works.)
Set a cookie. (My preferred solution, works great as long as cookies are enabled. Which, honestly, they may not be.)
However, the best option, especially on a mobile device is to keep the current framework of the page and get new content via ajax and load it into a content div on the current page.
I don't understand exactly what you're trying to do, but I would suggest you using an asynchronous ajax call to download the DOM of the next page.
Then you can apply the changes you want to that DOM, and finally you plug it into your current DOM.
An stub for that woul look like this:
$.ajax('path/to/next/page', {
async : true,
complete : function ajaxCallback(newSite) {
$item = $('YOURSELECTOR');
// Here you can make changes, such as CSS edition
$item.css({'background-color' : '#FF0000'});
// Since you want to make changes to the new site only if you did them in the first site...
if ($item.length > 0) {
$(newSite).find('YOURSELECTOR').css({'background-color' : '#FF0000'});
}
// Here you can append the new site to the DOM
}
});

Many different popups needed; Is it better to use one abstracted popup to handle every scenario

I have 3 different types of modal windows to handle different events. They popup to handle either:
1) Warnings, i.e. "hey, if you leave the page you will lose your work" kind of messages.
2) Dynamic data from a form the user previously filled out, i.e. "you are about to create a page with DataX: Data X, DataY: DataY, Date: March 28, 2012.
3) Form for the user to fill out.
I was originally trying to handle all 3 of the above scenarios with one set of html/css/javascript, just passing in data and modifying divs depending on situation. As I have expanded things, i'm noticing things being harder to maintain cleanly without being sloppy about it. I have a few questions which i'll list after I walk through how things are now.
Simplified HTML for modal popups:
<div id ="popup" style="display:none;">
<div class="modal-container">
<div class="modal">
<div class="modal-header">
<a class="close" href="# " title="Press Esc to close"><div id="close-label" title="Press Esc to close">Close</div></a>
<span id="top-header">WARNING</span>
</div>
<div class="modal-body">
<div class="modal-subhead">
<img class="subhead-icon" border="0" src="">
<span id= "header">WARNING</span>
</div>
<div class="modal-message"><span>If you leave this page, you will lose unsaved changed.</span></div>
<div class="modal-input-first">
<div class="modal-label"></div>
<div id="modal-input"></div>
</div>
<div class="modal-input-second">
<div class="modal-label"></div>
<div id="modal-input"></div>
</div>
<div class="modal-footer">
<a class="secondary" href="#">Cancel</a>
<span id = "button-secondary-label">or</span>
<span class="btn_container">
<span class="btn_left"></span>
<span class="btn_center">Continue</span>
<span class="btn_right"></span>
</span>
</div>
</div>
Right now this is located in a separate file with it's css and javascript and is loaded when the page is loaded.
In the main file I am changing the popup depending on what triggered the popup, just using jquery as such:
$('.modal-message').html('New Message');
$('.modal-subhead #header').text('New header');
The dynamic data is filled in similarly after first making the ajax request to get the data.
As I said, as things grow, i'm having to change a lot of this, and it's starting to feel sloppy. Especially as i'm having to make pixel perfect changes to the css for individual elements. Would it be best to have 3 completely separate sets of html to handle these? Where is the best place for this to live, is the separate file approach?
Is it better to keep adding separate elements as I need specific ones for certain instances, like so:
<div class="modal-input-specific-thing">
<div class="modal-label"></div>
<div id="modal-input"></div>
<div id="modal-input-2"></div>
</div>
Or to use jquery to change the structure of the html on the fly?
var new_input = 'modal-input' + count;
$('#modal-input').attr('id', new_input);
Is there a better method for pushing only the elements needed to a popup like this?
If I had 10-12 scenarios, which is possible as I keep expanding this. Is there a big enough performance hit to parsing 12 different sets of html/css every time page is loaded vs doing what i'm trying to do now...Making a generic/abstracted popup window, and push elements/data to it as the user needs?
Thanks!
I should do this with jQuery and jQuery UI. The jQuery UI has a real nice popup function called dialog. ( http://jqueryui.com/demos/dialog/ )
A working version that reconstruct your situation you will see here. ( http://jsfiddle.net/7GVmz/ )
There are a lot of options you can add so as buttons, callbacks on opening and closing. You can read all of it in the documentation on the jqueryui website ( http://jqueryui.com/demos/dialog/#option-disabled )
Html
<div id="popup-1" title="popup-1">
Hello World
</div>
<div id="popup-2" title="popup-2">
Hello World
</div>
<div id="popup-3" title="popup-3">
Hello World
</div>
JS
$(document).ready(function() {
$('#popup-1').dialog();
$('#popup-2').dialog();
$('#popup-3').dialog();
});​
Note
Its important that you load the jquery library and the jquery ui library.
​
I use SweetAlert for all my JavaScript alerts, it's a Better JavaScript Popup Box than the default and is really simple to use.
swal({<br>
title: "Are you sure you want to leave?",<br>
text: "You have unsaved changes!",<br>
type: "warning",<br>
showCancelButton: true,<br>
confirmButtonClass: "btn-danger",<br>
confirmButtonText: "Yes, Exit!",<br>
closeOnConfirm: false<br>
},<br>
function(){<br>
swal("Deleted!", "Your imaginary file has been deleted.", "success");<br>
});<br>
A full tutorial is here - https://kodesmart.com/kode/javascript-replacement-alert-box

Categories

Resources