Javascript - best way to handle post-load generated content - javascript

I've been wondering how to efficiently and generically process content that is generated after any user action.
For instance, let's say my script processes all paragraphs of Facebook at page load in order to make them blink. What would be the most responsive way to make the text that is displayed later (because of infinite scroll e.g.) blink ?
Thanks in advance for your ideas,
Rolf

Personally, I define a function called dom_mods() that modifies the page in order to apply any special effects such as autocompletion, default value for <select>, auto-resizing textareas and so on. Whenever I add content to the document, I call dom_mods().
The only catch is to make sure you don't affect the same elements twice, or if you do it needs to not make a difference. For instance, there might be a class that defines a set of elements to affect, so the class should be removed by dom_mods() so it doesn't get the treatement twice.

You would add the blink function to the parent object that would encompass all the children.
In other words if you use jquery you would specify the event selector as (".parent .child") when registering the child blink event. This way, you don't need to register any additional jquery "dom_mods" function or call anything else which wastes memory and time.

Related

Hide frame from other frameset

I am trying to hide (or edit inline attribute) a frame from an other framset by clicking a button.
I used : $(".HiddenFrame").hide();
But seems that I can not find the item.
JSFiddle
"As far as my understanding of things goes, you need to perform actions like hide on divs. Basically, whatever you are trying to affect needs to respond to the css display attribute. If you must use frames, I would strongly suggest you use divs instead, then you will need to write some jQuery that actually removes the frame from the DOM instead of just trying to hide it."
Source :stackoverflow
and see this Link

How to handle dynamically-added DOM elements for progressive enhancement without knowing the method of adding?

I have a simple script that that "progressively enhances" specific <input> elements with a draggable slider (demo of the jQuery plugin).
Additional <input> elements may be added, and the whole thing will be placed in many different scenarios (it's a pluggable frontend widget). In other words, I cannot hook onto some "Add Another Slider" button's click event, because I have no idea where those additional elements may come from (it may be a button, several buttons, some AJAX call, etc).
To handle those additional elements, currently I'm using:
// for any dynamically added elements:
setInterval(find_and_init_all_sliders_that_are_not_yet_inited, 200);
Is there a better way?
TL;DR:
I wanna run a function each time new DOM elements are added. But I have no info or control on how or where those new elements will be added.

Controlling the activation of the default transition in viewmodels

My question is quite simple and needs no special explanation.
In Durandal, is it possible to control whether or not to use transition when switching from/to a viewmodel?
The reason why I want to be able to deactivate the animation is as follows:
I have a search form module quicksearch.js in my shell/masterpage that is accessible from anywhere. What it does is validate the input and then simply redirect to the results page results.js passing the search parameters in an URL after hash. The results.js takes care of querying the server.
When the quicksearch.js module is used while on a page other than results.js, the animation is triggered and it's desired behavior. However, when on results.js and using quicksearch.js, the only thing that changes in URL is the parameter string (module name right after the hash is left unchanged). Still, this goes through all the lifecycle of activating results.js again, with animating from results.js to results.js and that looks pretty bad.
So, is there any way to, under a condition, prevent Durandal from animating the content and just compose and bind the view?
I haven't found a way to control the transition process from my viewmodel, I doubt there is a way to do it.
Yet, the reason I asked was that I wanted to prevent Durandal from animating when navigating to the current page with different hash query string (changing this query string does trigger the navigation). The solution was to create a custom transition and to check whether the target view id is or isn't the same as the current view id. rely relied on
context.activeView.dataset.view === context.child.dataset.view;
where context.activeView is the currently attached view and context.child is the view that is about to be bound. Then, if these ids are different, I trigger the animation and if not, I simply hide context.activeView and show the other.
That's it for this case

Why focus an input on page load instead of inline?

Almost all web pages that I see designed to set the focus to an input box add the code into a body onload event. This causes the code to execute once the entire html document has loaded. In theory, this seems like good practice.
However, in my experience, what this usually causes is double work on the user, as they have already entered data into two or three fields and are typing into another when their cursor is jumped back without their knowledge. I've seen a staggering number of users type the last 2/3 of their password into the beginning of a username field. As such, I've always placed the JS focus code immediately after the input to insure there is no delay.
My question is: Is there any technical reason not to place this focus code inline? Is there an advantage to calling it at the end of the page, or within an onload event? I'm curious why it has become common practice considering the obvious practical drawbacks.
A couple thoughts:
I would use a framework like jQuery and have this type of code run on $(document).ready(.... window.onload doesn't run until everything on the page is fully loaded, which explains the delay you have experienced. $(document).ready(... runs when jQuery determines the DOM has been loaded. You could probably write the same sort of logic without jQuery, but it varies by browser.
I prefer to keep my Javascript separate from my HTML because it allows for a cleaner separation of concerns. Then your behavior is then kept separate from your document structure which is separate from your presentation in your CSS. This also allows you to more easily re-use logic and maintain that code — possibly across projects.
Google and Yahoo both suggest placing scripts at the bottom of the html page for performance reasons.
The Yahoo article: http://developer.yahoo.com/performance/rules.html#js_bottom
You should definitely place the script in the appropriate place if it means the correct user experience -- in fact I would load that part of the script (Used for tabbing inputs) before the inputs to ensure it always works no matter how slow the connection.
The "document.ready" function allows you to ensure the elements you want to reference are in the dom and fires right when your whole document dom is loaded (This does not mean images are fully loaded).
If you want you could have the inputs start out as disabled and then reenable them on document ready. This would handle the rare case the script is not ready yet when the inputs are displayed.
Well if you call it before whole page has loaded you really don't know if the element already has been loaded when you make your call. And if you make your call in pre-hand you should check if the element really exists even if you know it always should.
Then to make the call inline, which might seem ideal. But on the other hand it's really bad if a page takes that long to load that you can make several inputs during the loading phase.
Also you could check if input has been made etc.
Also it is possible to check if any input on page contains focus if($("input::focus, textarea::focus").length)... and otherwise set focus on desired input.
Use the autofocus HTML attribute to specify which element should initially receive focus. This decouples JavaScript and gracefully degrades in older browsers.

Is it more efficient to keep DOM elements on the page or to re-render them as needed?

I have a dialog box that has settings associated with it. When the user clicks the "settings" button, a form is displayed so they can modify them.
What is more efficient:
to have the settings div exist hidden on the page and display when needed
OR
to create the settings div and populate it with data when needed?
In the first scenario you don't need to create the DOM elements and populate them every time, but if there are many dialog boxes open at once (a common situation) then the amount of elements on the page is pretty large and many of them are not going to be used often. But in the second situation, elements are created and appended to the DOM which gets expensive.
I'd suggest you to "cache" your html on the page, but enforce browser to do not render it until necessary (until user request the data, or simply scroll to it). The main idea is to add your html (with data) to the page, but comment it out. For example,
<div id="cached-html">
<!--
<div>
...some custom html here
</div>
-->
</div>
Then once user requested the html, you can do the following:
var html = document.getElementById('cached-html'),
inner = html.innerHTML;
html.innerHTML = inner.substring(4, inner.length - 4);
Pros. is that you don't bother your browser with initial rendering (later you can simply user display:none to hide it again), so your page renders faster.
And another note - if your data (and as a consequence inner html) changes frequently, then it will be better to re-render it each time user request it, but if it is almost static, then hide/show should be more effective.
There can be problems either way, it depends on your page. If you already have a lot of elements on the page, it may be better load add them when you need them. If your page is already very "scripty" you may want to load the elements and show them when needed.
The real question is what would be better for your page, more script, or more dom elements.
When you have to display same setting div at multiple places.
Keeping that hidden is a better solution.
Remember that creating a new dom element or cloning a existing dom element gives almost same performance, but for code clarity/maintainence cloning or template is better.
Implementation using template: Make a template of div setting and keep that hidden:
<div class="template_setting">
Your settings(children of template_setting)
</div>
Javascript/Jquery code:
-Whenever someone opens a dialogue box, make a clone of childrens of template_setting and append to div_dialogue.
-As you may have multiple templates on the same page( which is not always true).
Apply a custom event on the id of newly created setting div.( keep id of each setting div different, you can increment each one by some character/number).
$('#dialogue_opener').click(function(event){
$('.template_setting').children().clone().appendTo(div_dialogue)
.trigger('adjustSettingID');
Consider a hybrid solution. Load the "settings" div after the page is ready. This way, the user won't feel the extra "expense", and you'll have the div ready for when you need it.
I've typically seen that rendering from JavaScript is pretty darn fast. I've built lots of "just in time" menus, grids, and forms and the users can't tell the difference. The nice thing about it is that you don't have to keep a form current, just blow it away and default everything to the data in you settings object. Makes for cleaner code in my opinion.

Categories

Resources