I am relatively new to web-programming and am looking for a simple pattern to show a "loading"/waiting view for the web. Before I say anything else, I am sending only the minimum amount of data from the server, and start sending the JS/HTML resources to client while the client is using AJAX to request more data from the server (this might be suboptimal but bear with me). So basically, in theory this should mean the web view pops up earlier initially, but spends more time loading some of the data and corresponding subviews. Thus the need for a loading view.
So we have the standard jQuery function .ready()
fetchSomeDataAsynchronously(); //self-explanatory
$(document).ready(function () {
//should I load waiting view here or can I initialize it earlier??
window.mainUserHomeView = new MainUserHomeView({el: $("#user-home-main-div")});
window.mainUserHomeView.render();
window.userHomeMainTableView = new UserHomeMainTableView({el: $("#user-home-main-table-div")});
window.userHomeMainTableView.render();
fetchTeamSnapTeams(); //fetch more data asynchronously
});
Maybe my question is simply - can I show a loading screen before .ready() fires and what does that look like?
Yes you can. Just include the script to show the view in your HTML's head or at the beginning of the body. Make sure that you put it after you've loaded your required resources (e.g. jQuery) though.
Simplified example:
<html>
<head>
<script type="text/javascript">
function showLoadingView() {
// ...
}
showLoadingView();
</script>
</head>
<body>
<!-- ... -->
</body>
</html>
Related
Is there a way I can wrap an external JS script embed with lazy-load behavior to only execute when the embed is in the viewport?
Context: I have an external javascript embed that when run, generates an iframe with a scheduling widget. Works pretty well, except that when the script executes, it steals focus and scrolls you down to the widget when it’s done executing. The vendor has been looking at a fix for a couple weeks, but it’s messing up my pages. I otherwise like the vendor.
Javascript embed call:
<a href=https://10to8.com/book/zgdmlguizqqyrsxvzo/ id="TTE-871dab0c-4011-4293-bee3-7aabab857cfd" target="_blank">See
Online Booking Page</a>
<script src=https://d3saea0ftg7bjt.cloudfront.net/embed/js/embed.min.js> </script> <script>
window.TTE.init({
targetDivId: "TTE-871dab0c-4011-4293-bee3-7aabab857cfd",
uuid: "871dab0c-4011-4293-bee3-7aabab857cfd",
service: 1158717
});
</script>
While I'm waiting for the vendor to fix their js, I wondered if lazy-loading the JS embed may practically eliminate the poor user experience. Warning: I'm a JS/webdev noob, so probably can't do anything complicated. A timer-based workaround is not ideal because users may still be looking at other parts of the page when the timer runs out. Here are the things I’ve tried and what happens:
I tried:
What happened:
Add async to one or both of the script declarations above
Either only shows the link or keeps stealing focus.
Adding type=”module” to one or both script declarations above
Only rendered the link.
Wrapping the above code in an iframe with the appropriate lazy-loading tags
When I tried, it rendered a blank space.
Also, I realize it's basically the same question as this, but it didn't get any workable answers.
I actually also speak french but I'll reply in english for everybody.
Your question was quite interesting because I also wanted to try out some lazy loading so I had a play on Codepen with your example (using your booking id).
I used the appear.js library because I didn't really want to spend time trying some other APIs (perhaps lighter so to take in consideration).
The main JS part I wrote is like this:
// The code to init the appear.js lib and add our logic for the booking links.
(function(){
// Perhaps these constants could be put in the generated HTML. I don't really know
// where they come from but they seem to be related to an account.
const VENDOR_LIB_SRC = "https://d3saea0ftg7bjt.cloudfront.net/embed/js/embed.min.js";
const UUID = "871dab0c-4011-4293-bee3-7aabab857cfd";
const SERVICE = 1158717;
let vendorLibLoaded = false; // Just to avoid loading several times the vendor's lib.
appear({
elements: function() {
return document.querySelectorAll('a.booking-link');
},
appear: function(bookingLink) {
console.log('booking link is visible', bookingLink);
/**
* A function which we'll be able to execute once the vendor's
* script has been loaded or later when we see other booking links
* in the page.
*/
function initBookingLink(bookingLink) {
window.TTE.init({
targetDivId: bookingLink.getAttribute('id'),
uuid: UUID,
service: SERVICE
});
}
if (!vendorLibLoaded) {
// Load the vendor's JS and once it's loaded then init the link.
let script = document.createElement('script');
script.onload = function() {
vendorLibLoaded = true;
initBookingLink(bookingLink);
};
script.src = VENDOR_LIB_SRC;
document.head.appendChild(script);
} else {
initBookingLink(bookingLink);
}
},
reappear: false
});
})();
I let you try my codepen here: https://codepen.io/patacra/pen/gOmaKev?editors=1111
Tell me when to delete it if it contains sensitive data!
Kind regards,
Patrick
This method will Lazy Load HTML Elements only when it is visible to User, If the Element is not scrolled into viewport it will not be loaded, it works like Lazy Loading an Image.
Add LazyHTML script to Head.
<script async src="https://cdn.jsdelivr.net/npm/lazyhtml#1.0.0/dist/lazyhtml.min.js" crossorigin="anonymous" debug></script>
Wrap Element in LazyHTML Wrapper.
<div class="lazyhtml" data-lazyhtml onvisible>
<script type="text/lazyhtml">
<!--
<a href=https://10to8.com/book/zgdmlguizqqyrsxvzo/ id="TTE-871dab0c-4011-4293-bee3-7aabab857cfd" target="_blank">See
Online Booking Page</a>
<script src=https://d3saea0ftg7bjt.cloudfront.net/embed/js/embed.min.js>
</script>
<script>
window.TTE.init({
targetDivId: "TTE-871dab0c-4011-4293-bee3-7aabab857cfd",
uuid: "871dab0c-4011-4293-bee3-7aabab857cfd",
service: 1158717
});
</script>
-->
</script>
</div>
I make use of jQuery and history.js to manage dynamic transitions between partial-pages; such that I avoid reloading entire documents. Some of these partial-pages call their own unique javascript files. While the transitions between pages work well, remnants of executed javascript remain active after the partial page that called it has been dynamically replaced.
How can I unload javascript that was introduced with a dynamic page load, and later asynchronously replaced by another page?
The finer details
Master template
My master template (used for all pages) can be thought of as a simple:
<html>
<head>
<script>
//scripts to manage asynchronous loading of partial-pages into #content div
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
User profile
One partial page that renders inside the #content div is for a user's Profile:
<script src="profile.js"></script>
<form>
<input type="file" name="profile-picture">
</form>
The contents of profile.js are similar to:
$(function() {
$('input').change(function() {
// upload profile picture asynchronously
});
});
User settings
Another partial page that is loaded inside the #content div of the master template is the user's Settings:
<script src="settings.js"></script>
<form>
<input type="text" name="first-name">
<input type="text" name="last-name">
</form>
The contents of settings.js are similar to:
$(function() {
setInterval(function() {
// auto-submit form every 10 seconds
$('form').submit();
}, 10000);
}
});
The problems
Certain javascript functions continue to run (e.g. setInterval) after the partial page that called them has been replaced by another.
This business of loading new javascript for each partial page feels messy; but for the life of me, I can't find any recommendations for best practices.
What is the better way to achieve this effect of dynamic partial-page loading/unloading while allowing page-specific scripts for each partial page?
Thank you!
Firstly...once you load javascript...you can't unload it
The setInterval problem will require using clearInterval
Declare some esoteric name that would make it fairly unique as a global variable when you initialize setiIterval; Make sure you declare the var outside of $(document).ready before using it
var my_super_form_submitter
$(document.ready)function(){...
my_super_form_submitter=setInterval(func.....
Then whenever you load a new page
if(my_super_form_submitter)
clearInterval(my_super_form_submitter)
As for collisions with other methods....you could adopt a content class protocol for your page specific code. On each page load, change class of content div...then use that class within selectors for jQuery
For first problem:
Question is what functions continues to run after replacing packages. SetInterval that you mentioned uses js timers, and simply replacing package wont stop timer automatically.
You should clear all timers started via setInterval before replacing.
E.g.
$(function() {
var timer = setInterval(function() {
// auto-submit form every 10 seconds
$('form').submit();
}, 10000);
}
function uninitialize(){
clearInterval(timer);
}
Just call uninitialize before replacing package, and it should work.
UnfortunatelyI don't know any proper way for loading partial pages, but I hope it helps you somehow (:
I'm looking for best practices for using javascript/jQuery snippets in an asp.net project. I know that it is best to put all the scripts in a separate file rather than inline. That's good. It is easy to move these script functions to a common file (may be a couple of different ones to even out the performance of loading a single large file for small functions).
But there is some jQuery stuff that needs to happen on document.Ready on each page. How will I move this to a common .js file? I would like to avoid one script per page as it would be just too many.
For example, say Page1 has a need to manipulate a few radio buttons on load and has the following script inline. (just for illustration)
<script>
$(document).ready(function() {
//check checkboxes
if(true)
call function1();
});
</script>
Same with Page2 but for some other condition, calling different function function2.
I can move the function1 and function2 to a common .js file but how about the document ready sections. Should that stay inline? I assume so because otherwise I'm not sure how the common.js will differentiate between document.ready for different pages.
Then does it defeat the purpose of not having inline javascript? If anyone can throw some light into this, it is much appreciated.
I did some research, but probably due to incorrect keywords, so far I haven't been able to find any good information along the same lines. Unobtrusive JavaScript seems promising in the comments below.
You should specify what behaviors should exist within the HTML using data-* attributes.
You can then use a single universal piece of Javascript code to read these attributes and apply behaviors.
For example:
<div data-fancy-trick="trick-3">...</div>
In the JS file, you can write something like
$('[data-fancy-trick]'.each(function() {
var trickName = $(this).data('fancy-trick');
switch (trickName) {
...
}
});
For real-life examples of this technique, look at Bootstrap's Javascript components.
You can simply have separate js files per page and include them in relevant pages. For shared script code, have a common js file. Following your example:
common.js
var myCommonVar = {};
function myCommonFunction(...){
...
}
page1.js
$(document).ready(function() {
...
function1();
...
});
page2.js
$(document).ready(function() {
...
function2();
...
});
page1.html
...
<script src='/js/common/js'></script>
<script src='/js/page1.js'></script>
...
page2.html
...
<script src='/js/common/js'></script>
<script src='/js/page2.js'></script>
...
Consider the usage of AMD (Asynchronous Module Definiton) design pattern. Put your JavaScript code into modules and on each page use just those you really need to. For example requirejs does a great job and I've been using it with success. If you have a bigger project you can split your modules into namespaces. This approach will keep excellent code maintainability and it's reliable. You simply put the "starter" javascript file on each page and load only those required modules you need to work with per each page.
There are many ways to deal with this problem, either using a JavaScript Framework that is aiming to treat your website as a 'Webapp' (Angular and Ember among the popular), or using your own custom script that will do just that - invoking the appropriate JavaScript per loaded page.
Basically, a custom script that will be able to handle it, will have to make use of (pseudo) 'Namespaces' to separate modules/pages code sections.
Assuming you have 2 hypothetical pages, Home and Browse, Simplified code sample may look like this:
HTML:
<body data-page="Home">
Global.js:
var MyApp = {}; // global namespace
$(document).ready(function()
{
var pageName = $('body').data('page');
if (pageName && MyApp[pageName] && MyApp[pageName].Ready)
MyApp[pageName].Ready();
});
Home.js:
MyApp.Home = MyApp.Home || {}; // 'Home' namespace
MyApp.Home.Ready = function()
{
// here comes your 'Home' document.ready()
};
Browse.js:
MyApp.Browse = MyApp.Browse || {}; // 'Browse' namespace
MyApp.Browse.Ready = function()
{
// here comes your 'Browse' document.ready()
};
MyApp.Browse.AnotherUtilFunc = function()
{
// you could have the rest of your page-specific functions as well
}
Also, since you're using ASP.NET MVC, sometimes your Controller name may fit as the qualified page name, you can set it automatically in your Layout.cshtml (if you have one):
<html>
<head>
</head>
<body data-page="#ViewContext.RouteData.Values["Controller"].ToString()">
#RenderBody()
</body>
</html>
I think its not worth stuffing up everything in a single file and separating them with conditional statements, just to avoid adding a reference on the respective file.
If you have code that can be called on 2,3 or more pages, then we can opt for having them in a common file. But if its going to be called on a single page then we must write code on the respective page only. This will also increase the overhead of declaring the functions that are not going to be called on the current page
And when you are using the common js file, then you don't need to worry about the $(document).ready(); event, you can use a single ready event in the common file and separate the code by using conditional statements.
The new versions of the script manager will combine everything into one blob of a script. In theory it makes fewer round trips and things run faster. In practice you could end up with several large scripts that are nearly identical and each page needs its own blob of a script. If your making one of those never change the url website pages then this is the way to go.
I came up with these best practices when I was working with jquery on ASP.Net
Load Jquery in your master page above the first script manager. Jquery is now available on every page. The browser will only get it once and cache it.
If bandwidth is an issue use a jquery loader like googleload or MS content delivery network
Document.load is always at the bottom of the page to guarantee that everything needed is already loaded.
From my blog that I haven't updated in years...Google Load with ASP.Net
One common way to address this problem would be to have your common script include followed by a per-page script element:
<!-- In 'shoppingcart.html' -->
<script src="main.js"></script>
<script>
// Let there be a onDomReady JS object inside main.js
// that defines the document.ready logic on a per-page basis
$(document).ready(onDomReady.shoppingCart);
</script>
Great question, I have been dealing with the same thing.
Here is what I have been doing:
Have your $(document).ready() call different init functions (if they exist), where each .js file has its own init which adds event listeners and loads functions, messes with css, etc.. Each .js file is separated out into different pieces of functionality.
This way you have one document ready that calls all of your initializers. So each page would include the .js functionality it needs. This way you can separate out what is different.
ex:
ready.js:
$(document).ready(function(){
if (typeof menuNavInit == 'function'){
menuNavInit();
}
if (typeof menuNavDifferentInit == 'function'){
menuNavDifferentInit();
}
//other .js functionality
});
menuNav.js
function menuNavInit(){
$("#menu").on('click', menuNavClick)
}
function menuNavClick(){
//do something
}
menuNavDifferent.js
function menuNavDifferentInit(){
$("#menu").on('click', menuNavDifferentClick)
}
function menuNavDifferentClick(){
//do something else
}
page1.html
...
<script src='scripts/ready.js'></script>
<script src='scripts/menuNav.js'></script>
...
page2.html
...
<script src='scripts/ready.js'></script>
<script src='scripts/menuNavDifferent.js'></script>
...
While my code calculates, Id like the submit button to go from the "RUN" that it is now to the loading gif that I have. Now when I click the RUN button, I also need a certain script to run which calculates all sorts of data and returns it back to the page. I wrote a function that holds the other two function and calls them in sequence. I even added a 3rd function that would revert back the submit button but I can't seem to figure this out.
The website is www.fsaesim.com/simulation.html which would be much easier to see the code, however attached is the code.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="framework.js"></script>
<script type="text/javascript">
function ShowCalculation() {
var results = Main($("#vehicleWeightTxt").val(), $("#tireChoiceSel").val(), $("#wheelBaseTxt").val(), $("#wheelRadiusTxt").val(), $("#trackWidthTxt").val(), $("#hcgTxt").val(), $("#weightDistributionTxt").val(), $("#shiftRpmTxt").val(), $("#ntTxt").val());
$('#outputTotalTime').empty();
$('#outputTotalPoints').empty();
$('#outputFuelUsed').empty();
$('#outputTimeOpenThrottle').empty();
$('#outputCorneringTimeTotal').empty();
$('#outputTotalStraightSectionTime').empty();
$('#outputTotalNumberOfShifts').empty();
$('#outputTractionLimitedDuration').empty();
$('#outputMeanLongAccel').empty();
$('#outputMeanHorsepower').empty();
$('#outputAccelerationTime').empty();
$('#outputMeanAccelerationLongAccel').empty();
$('#outputAccelerationTractionLimitedTime').empty();
$('#outputAccelerationTotalPoints').empty();
$('#outputAccelerationWideOpenThrottlePercentage').empty();
$('#outputAccelerationShifts').empty();
$('#outputAccelerationTrapSpeed').empty();
$('#outputTotalEnduranceTime').empty();
$('#outputTotalEndurancePoints').empty();
$('#outputTotalEnduranceFuelUsed').empty();
$('#outputTotalWOTPercentage').empty();
$('#outputTotalEnduranceShifts').empty();
$('#outputTotalEnduranceTractionLimitedTime').empty();
$('#outputTotalEnduranceAcceleration').empty();
$('#outputSkidpadTime').empty();
$('#outputSkidpadPoints').empty();
$('#outputSkidpadVelocity').empty();
$('#outputSkidpadAcceleration').empty();
$('#outputAutocrossTime').empty();
$('#outputAutocrossPoints').empty();
$('#outputAutocrossTotalShifts').empty();
$('#outputAutocrossTractionLimitedTime').empty();
$('#outputAutocrossVelocity').empty();
$('#outputAutocrossWOTPercentage').empty();
$('#outputAutocrossLongitudinalAcceleration').empty();
$('#outputMaxHorsepower').empty();
$("#outputTotalTime").append(results.output1);
$("#outputTotalPoints").append(results.output2);
$("#outputFuelUsed").append(results.output3);
$("#outputTimeOpenThrottle").append(results.output4);
$("#outputCorneringTimeTotal").append(results.output5);
$("#outputTotalStraightSectionTime").append(results.output6);
$("#outputTotalNumberOfShifts").append(results.output7);
$("#outputTractionLimitedDuration").append(results.output8);
$("#outputMeanLongAccel").append(results.output9);
$("#outputMeanHorsepower").append(results.output10);
$("#outputMaxHorsepower").append(results.output27);
$("#outputAccelerationTime").append(results.output11);
$("#outputMeanAccelerationLongAccel").append(results.output12);
$("#outputAccelerationTractionLimitedTime").append(results.output13);
$("#outputAccelerationTotalPoints").append(results.output14);
$("#outputAccelerationWideOpenThrottlePercentage").append(results.output15);
$("#outputAccelerationShifts").append(results.output16);
$("#outputAccelerationTrapSpeed").append(results.output17);
$("#outputTotalEnduranceTime").append(results.output1);
$("#outputTotalEndurancePoints").append(results.output2);
$("#outputTotalEnduranceFuelUsed").append(results.output3);
$("#outputTotalWOTPercentage").append(results.output4);
$("#outputTotalEnduranceShifts").append(results.output7);
$("#outputTotalEnduranceTractionLimitedTime").append(results.output8);
$("#outputTotalEnduranceAcceleration").append(results.output9);
$("#outputSkidpadTime").append(results.output18);
$("#outputSkidpadPoints").append(results.output19);
$("#outputSkidpadVelocity").append(results.output20);
$("#outputSkidpadAcceleration").append(results.output21);
$("#outputAutocrossTime").append(results.output22);
$("#outputAutocrossPoints").append(results.output23);
$("#outputAutocrossTotalShifts").append(results.output24);
$("#outputAutocrossTractionLimitedTime").append(results.output25);
$("#outputAutocrossVelocity").append(results.output26);
$("#outputAutocrossWOTPercentage").append(results.output4);
$("#outputAutocrossLongitudinalAcceleration").append(results.output9);
}
function mouseClick() {
document.getElementById("submitButton").src = "images/loading.gif";
}
function revertBack() {
document.getElementById("submitButton").src = "images/simulationSubmit.png";
}
function simulationEvents() {
mouseClick();
ShowCalculation();
revertBack();
}
</script>
<center><img src="images/simulationSubmit.png" alt="" id="submitButton" onmouseover="mouseOver()" onmouseout="mouseOut()" onclick="simulationEvents(); return false;" /></center>
Since all your processing is being done in javascript, that will tie up your script until it finishes.
Javascript isn't multithreaded, it does one task at a time until that task is done.
Generally, when you see that animated gif while a form is being processed the page is using AJAX or something similar. The number crunching is happening server-side using PHP or Python or something like that.
The animation just runs while the javascript waits to hear back from the server-side script.
You might be able to work around it somewhat with this tutorial but that seems like overkill for this situation. The easiest thing would probably be to send the form data to a server-side script or just deal with not having an animation during processing.
Edit: If you're wanting to learn how to do AJAX, here's a tutorial that uses jQuery, which your site is already loading.
I have tried it using jQuery but it is not working.
<script>
$("a").click(function () {
$.post("http://www.example.com/trackol.php", {result: "click"
}, "html");
});
</script>
out
To get the best results you should change two things in your approach
Use onmousedown instead of click - this way you get a few extra milliseconds to complete the tracking request, otherwise the browser might not start the connection to your tracker at all as it is already navigating away from the original page. The downside is that you might get some false-positive counts, since the clicking user might not finish the click (eg. keeps the mousebutton down and moves the cursor away from the link) but overall it's a sacrifice you should be willing to make - considering the better quality of tracking.
Instead of an Ajax call ($.post('...')) use an image pre-fetcher (new Image().src='...'). The fact that the tracker is not an image is not relevant in this case because you don't want to use the resulting "image" anyway, you just want to make a request to the server. Ajax call is a two way connection so it takes a bit more time and might fail if the browser is already navigating away but the image pre-fetcher just sends the request to the server and it doesn't really matter if you get something back or not.
So the solution would be something like this:
<script>
$(document).ready(function() {
$("a").mousedown(function (){
new Image().src= "http://www.example.com/trackol.php?result=click";
});
});
</script>
out
Instead of using JavaScript to call a php tracking script, you could just link to your tracking script directly and have it in turn redirect the response to the ultimate destination, something like this:
out
and in the PHP script, after you do your tracking stuff:
...
header("Location: $dest");
As mentioned, the problem is you’re not running the script after the DOM has loaded. You can fix this by wrapping your jQuery script inside $(function() { }, like so:
This works:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tracking outgoing links with JavaScript and PHP</title>
</head>
<body>
<p>Test link to Google</p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
$('a').click(function() {
$.post('http://www.example.com/trackol.php', { result: 'click' }, 'html');
});
});
</script>
</body>
</html>
See it in action here: http://jsbin.com/imomo3