Switch pages without reload - javascript

My Electron App has an Menu in the every .html Page witch is controlled by an controller.js
$(document).ready(function() {
const app = require("electron").remote.app;
const { remote } = require("electron");
$("#btn1").click(function() {
window.location = "index.html";
});
$("#btn2").click(function() {
window.location = "aaa.html";
});
$("#btn3").click(function() {
window.location = "bbb.html";
});
$("#btn4").click(function() {
window.location = "ccc.html";
});
$("#btn5").click(function() {
window.location = "ddd.html";
});
$("#btn6").click(function() {
window.location = "eee.html";
});
$("#btn7").click(function() {
window.location = "fff.html";
});
});
In the every Html Page i have in the head section so the controller.js can work! My question now is how to make this without to reload all the time the window when switching the page?
For example When I go to aaa.html It feels like in the Browser a have for a few Milliseconds a White screen then it goes to the new Page, How I can make this work without White Window when Clicking a Button to go to a new Page? I want the Content to be loaded when I click the Button without this Browser feeling.
Any Ideas how I can do this or what I can do better here? Thank you

To answer the question technically : you could get the content of your pages using the fetch API, and then parse them using a DOMParser and then replace the current content of your page (or just a part of it, say not the header and footer, but everything else) with what you just parsed, using the history API
Making this all work nicely together is not straightforward though, and you will never get rid of some level of rendering 'flashes' in some places in most cases.
What you probably want to build is a single page application, I suggest you check out React, Vue or Angular and build from those
Edit :
An other solution is to load everything upfront and then inject/remove elements using javascript, for this solution, I would recommend using templates (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template)

Besides solving the page request problem, i would advise to adopt available frameworks and libraries that support in building single page applications. A lot of work has already been done for you.
Personally i would use React with the react-router package to create an SPA. If you want to reduce flashes between transitions, you need to avoid re-rendering the whole page. This is exactly what UI libraries like React do.

Related

Handling url targeted PHP page with custom jQuery loaded content

First I used include('pageName.php'); for every page I wanted to load.
Now I decided to rewrite everything and to load a page in a <div id="page_content"></div> with the jQuery function: $('#page_content').load(pageurl, {access:true});
I hope this is the best practice. Because I want to reduce load time on my web application by not refreshing the whole website with all CSS and JS files but just to refresh content when clicked on a new page.
Currently I am using the following function to load pages into the division and to pushState to history:
//Dynload pages
$("a[rel='dynload']").click(function(e) {
e.preventDefault();
var page = $(this).attr("page");
var pageurl = "pages/" + page + ".php";
$('#page_content').load(pageurl, {access:true});
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',page);
}
//stop refreshing to the page given in
return false;
});
This works perfectly.
I have this button that triggers this function and gives for attribute page="index_content" . The function will load this page to the division and the state is being pushed into the history.
However. We get an url something like this: https://mywebsite.com/index_content
The problem is, when I load this specific URL into my browser I get : "Page not found" ofcourse, because it is trying to search for the index_content folder which does not exist.
Is there a way to check the url by my PHP/jQuery script and to load the correct page into the division? If not, how can I solve this for a generic case.
When I add a new page, I want to spend no- to very less time on the pageswitcher function.
In that way I can also handle non-existing pages.
Thanks in advance!

Make Iron Router reload page when clicking on the same link

I just started playing around with Meteor and Iron Router to create a simple site. There are a few links on the nav bar of the site and one of them is called random. The idea is that when a user clicks it, a random post would display at the page.
Now Iron Router seems to prevent a page from reloading if it's the same link with the current one. That's a great feature except in my case I need it to reload so the user can see a new post.
Here's the relevant code:
Router.route('/random', function() {
console.log("running this!");
this.layout('SinglePostLayout', {
data: function () { return draw(Posts, {}) }
});
this.render('post');
The draw function returns a post in the collection. It's fun from perfect but that's not relevant here. I confirmed the code only ran once by using console.log.
Is there a way around this? I want to preserve the no reloading behaviour for all other links except for the random one. I've searched for answers for a while but couldn't find anything.
Thanks!
Since you are not using dynamic routes to show each post.
You can use the Location.reload() method from the window object, and use pure Javascript.
if(Meteor.isClient){
Template.home.events({
'click #randomHref':function(){
document.location.reload(true);
// Router.go('/') don't work.
}
})
}

How to pre-load (cache) an external page in jquery before redirecting to it?

I am doing a phonegap app.
I have an index.html page with a sign-in button that redirects to the website app.
When sign-in button was clicked, I wanted to have a loading gif to show while the page
is being cached/pre-loaded and redirect to the page when its done.
I would appreciate a sample script code.
I'm not even sure you need to use any jQuery or Javascript unless you want to dynamically take care of many cases like this. You can look into HTML5 prefetch to preload and cache the next page after login. So in the head of your document add:
<link rel="prefetch" href="http://example-site/next_page_after_login.html" />
You can read more about this on David Walsh blog here, or read more on MDN prefetch MDN
I accomplished a similar task using <iframe> elements. My phonegap app needed to load (local) pages, possibly modifying them via jQuery. Using plain redirects (via window.location) caused loading artifacts for two reasons:
images appeared as they were being loaded
the page state before jQuery modifications momentarily flashed.
I solved this problem by loading the page in a non-visible <iframe>, and making the <iframe> visible only after it had loaded and modifications had been made via jQuery. I supposed there are various ways to do this, but I did it by "juggling" <iframe> elements via their z-index.
I have created an annotated fiddle that is slightly simpler and adds a loading spinner:
http://jsfiddle.net/Leftium/L2HdV/ (Hat tip to Umidbek for the spinner!):
jQuery(document).ready(function ($) {
$app = $('.app');
// Attach behavior to Login button.
$('.login').on('click', function () {
$app.addClass('loading');
// Create an <iframe>.
$iframe = $('<iframe>');
// Set url of <iframe> to desired redirect URL.
// Note: the URL must be in the same domain,
// or set special HTTP headers to allow rendering inside an <iframe>.
$iframe.attr({src: 'http://doc.jsfiddle.net/'});
// Add <iframe> we just created to DOM.
$iframe.appendTo($('body'));
// When <iframe> has been loaded, remove <div> containing login button
// and loading spinner to reveal <iframe>.
$iframe.load(function() {
$('.app').remove()
});
});
});
This is very simple example:
http://jsfiddle.net/umidbek_karimov/DQ2wn/
Use css classes to manipulate visibility of the loader div and switch between pages.
jQuery(document).ready(function ($) {
$app = $('.app'),
$pages = $('.page');
$('.login').on('click', function () {
$app.addClass('loading');
$pages.removeClass('active').filter('.page-2').addClass('active');
setTimeout(function () {
$app.removeClass('loading');
}, 500);
});
$('.logout').on('click', function () {
$app.addClass('loading');
$pages.removeClass('active').filter('.page-1').addClass('active');
setTimeout(function () {
$app.removeClass('loading');
}, 500);
});
$app.removeClass('loading');
});
But if you need more complicated solution it's better to use some js frameworks, Knockout.js + some js router, or more powerful Angular.JS

Dynamic content accessibility issue

I'm working on a website and I want to be able to access the dynamic content on the Menu page from every other page on the website but when you try to access it from another page, it doesn't even leave the page. How do I get it to take me to the Menu page and also display exactly what was clicked. The function created for this is as displayed below
$(document).ready(function() {
jcps.fader(300, '#switcher-panel');
});
var _tagIndex = window.location.href.indexOf('#');
if (_tagIndex>=0) {
showContent(window.location.href.substr(_tagIndex));
}
Jquery History plugin is a rather common solution

How do I refresh a page using JavaScript?

How do I refresh a page using JavaScript?
Use location.reload().
For example, to reload whenever an element with id="something" is clicked:
$('#something').click(function() {
location.reload();
});
The reload() function takes an optional parameter that can be set to true to force a reload from the server rather than the cache. The parameter defaults to false, so by default the page may reload from the browser's cache.
There are multiple unlimited ways to refresh a page with JavaScript:
location.reload()
history.go(0)
location.href = location.href
location.href = location.pathname
location.replace(location.pathname)
location.reload(false)
If we needed to pull the document from
the web-server again (such as where the document contents
change dynamically) we would pass the argument as true.
You can continue the list being creative:
window.location = window.location
window.self.window.self.window.window.location = window.location
...and other 534 ways
var methods = [
"location.reload()",
"history.go(0)",
"location.href = location.href",
"location.href = location.pathname",
"location.replace(location.pathname)",
"location.reload(false)"
];
var $body = $("body");
for (var i = 0; i < methods.length; ++i) {
(function(cMethod) {
$body.append($("<button>", {
text: cMethod
}).on("click", function() {
eval(cMethod); // don't blame me for using eval
}));
})(methods[i]);
}
button {
background: #2ecc71;
border: 0;
color: white;
font-weight: bold;
font-family: "Monaco", monospace;
padding: 10px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.5s ease;
margin: 2px;
}
button:hover {
background: #27ae60;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This works on all browsers:
location.reload();
Lots of ways will work, I suppose:
window.location.reload();
history.go(0);
window.location.href=window.location.href;
To reload a page with jQuery, do:
$.ajax({
url: "",
context: document.body,
success: function(s,x){
$(this).html(s);
}
});
The approach here that I used was Ajax jQuery. I tested it on Chrome 13. Then I put the code in the handler that will trigger the reload. The URL is "", which means this page.
Edit2: The original question was "How to reload a page with JQUERY"! Downvoters take note.
Edit: Unfortunately, I'll have to take down this answer very soon because, the question has changed and the user seemed to not be very clear on what they were asking. Some users have commented that refreshing is different from reloading a page; See the revisions to this question [https://stackoverflow.com/posts/5404839/revisions] As far as I can tell, from the original question which was around refreshing a page with AJAX which is ASYNCHRONOUS ..., refreshing a page should imply getting new and updated content to the page. Anyway, this answer will soon go away./
If the current page was loaded by a POST request, you may want to use
window.location = window.location.pathname;
instead of
window.location.reload();
because window.location.reload() will prompt for confirmation if called on a page that was loaded by a POST request.
The question should be,
How to refresh a page with JavaScript
window.location.href = window.location.href; //This is a possibility
window.location.reload(); //Another possiblity
history.go(0); //And another
You're spoiled for choice.
You may want to use
location.reload(forceGet)
forceGet is a boolean and optional.
The default is false which reloads the page from the cache.
Set this parameter to true if you want to force the browser to get the page from the server to get rid of the cache as well.
Or just
location.reload()
if you want quick and easy with caching.
Three approaches with different cache-related behaviours:
location.reload(true)
In browsers that implement the forcedReload parameter of location.reload(), reloads by fetching a fresh copy of the page and all of its resources (scripts, stylesheets, images, etc.). Will not serve any resources from the cache - gets fresh copies from the server without sending any if-modified-since or if-none-match headers in the request.
Equivalent to the user doing a "hard reload" in browsers where that's possible.
Note that passing true to location.reload() is supported in Firefox (see MDN) and Internet Explorer (see MSDN) but is not supported universally and is not part of the W3 HTML 5 spec, nor the W3 draft HTML 5.1 spec, nor the WHATWG HTML Living Standard.
In unsupporting browsers, like Google Chrome, location.reload(true) behaves the same as location.reload().
location.reload() or location.reload(false)
Reloads the page, fetching a fresh, non-cached copy of the page HTML itself, and performing RFC 7234 revalidation requests for any resources (like scripts) that the browser has cached, even if they are fresh are RFC 7234 permits the browser to serve them without revalidation.
Exactly how the browser should utilise its cache when performing a location.reload() call isn't specified or documented as far as I can tell; I determined the behaviour above by experimentation.
This is equivalent to the user simply pressing the "refresh" button in their browser.
location = location (or infinitely many other possible techniques that involve assigning to location or to its properties)
Only works if the page's URL doesn't contain a fragid/hashbang!
Reloads the page without refetching or revalidating any fresh resources from the cache. If the page's HTML itself is fresh, this will reload the page without performing any HTTP requests at all.
This is equivalent (from a caching perspective) to the user opening the page in a new tab.
However, if the page's URL contains a hash, this will have no effect.
Again, the caching behaviour here is unspecified as far as I know; I determined it by testing.
So, in summary, you want to use:
location = location for maximum use of the cache, as long as the page doesn't have a hash in its URL, in which case this won't work
location.reload(true) to fetch new copies of all resources without revalidating (although it's not universally supported and will behave no differently to location.reload() in some browsers, like Chrome)
location.reload() to faithfully reproduce the effect of the user clicking the 'refresh' button.
window.location.reload() will reload from the server and will load all your data, scripts, images, etc. again.
So if you just want to refresh the HTML, the window.location = document.URL will return much quicker and with less traffic. But it will not reload the page if there is a hash (#) in the URL.
The jQuery Load function can also perform a page refresh:
$('body').load('views/file.html', function () {
$(this).fadeIn(5000);
});
As the question is generic, let's try to sum up possible solutions for the answer:
Simple plain JavaScript Solution:
The easiest way is a one line solution placed in an appropriate way:
location.reload();
What many people are missing here, because they hope to get some "points" is that the reload() function itself offers a Boolean as a parameter (details: https://developer.mozilla.org/en-US/docs/Web/API/Location/reload).
The Location.reload() method reloads the resource from the current
URL. Its optional unique parameter is a Boolean, which, when it is
true, causes the page to always be reloaded from the server. If it is
false or not specified, the browser may reload the page from its
cache.
This means there are two ways:
Solution1: Force reloading the current page from the server
location.reload(true);
Solution2: Reloading from cache or server (based on browser and your config)
location.reload(false);
location.reload();
And if you want to combine it with jQuery an listening to an event, I would recommend using the ".on()" method instead of ".click" or other event wrappers, e.g. a more proper solution would be:
$('#reloadIt').on('eventXyZ', function() {
location.reload(true);
});
Here is a solution that asynchronously reloads a page using jQuery. It avoids the flicker caused by window.location = window.location. This example shows a page that reloads continuously, as in a dashboard. It is battle-tested and is running on an information display TV in Times Square.
<!DOCTYPE html>
<html lang="en">
<head>
...
<meta http-equiv="refresh" content="300">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script>
function refresh() {
$.ajax({
url: "",
dataType: "text",
success: function(html) {
$('#fu').replaceWith($.parseHTML(html));
setTimeout(refresh,2000);
}
});
}
refresh();
</script>
</head>
<body>
<div id="fu">
...
</div>
</body>
</html>
Notes:
Using $.ajax directly like $.get('',function(data){$(document.body).html(data)}) causes css/js files to get cache-busted, even if you use cache: true, that's why we use parseHTML
parseHTML will NOT find a body tag so your whole body needs to go in an extra div, I hope this nugget of knowledge helps you one day, you can guess how we chose the id for that div
Use http-equiv="refresh" just in case something goes wrong with javascript/server hiccup, then the page will STILL reload without you getting a phone call
This approach probably leaks memory somehow, the http-equiv refresh fixes that
I found
window.location.href = "";
or
window.location.href = null;
also makes a page refresh.
This makes it very much easier to reload the page removing any hash.
This is very nice when I am using AngularJS in the iOS simulator, so that I don't have to rerun the app.
You can use JavaScript location.reload() method.
This method accepts a boolean parameter. true or false. If the parameter is true; the page always reloaded from the server. If it is false; which is the default or with empty parameter browser reload the page from it's cache.
With true parameter
<button type="button" onclick="location.reload(true);">Reload page</button>
With default/ false parameter
<button type="button" onclick="location.reload();">Reload page</button>
Using jquery
<button id="Reloadpage">Reload page</button>
<script type="text/javascript">
$('#Reloadpage').click(function() {
location.reload();
});
</script>
You don't need anything from jQuery, to reload a page using pure JavaScript, just use reload function on location property like this:
window.location.reload();
By default, this will reload the page using the browser cache (if exists)...
If you'd like to do force reload the page, just pass a true value to reload method like below...
window.location.reload(true);
Also if you are already in window scope, you can get rid of window and do:
location.reload();
use
location.reload();
or
window.location.reload();
<i id="refresh" class="fa fa-refresh" aria-hidden="true"></i>
<script>
$(document).on('click','#refresh',function(){
location.reload(true);
});
</script>
This works for me.
function reload(){
location.reload(true);
}
Use onclick="return location.reload();" within the button tag.
<button id="refersh-page" name="refersh-page" type="button" onclick="return location.reload();">Refesh Page</button>
If you are using jQuery and want to refresh, then try adding your jQuery in a javascript function:
I wanted to hide an iframe from a page when clicking oh an h3, for me it worked but I wasn't able to click the item that allowed me to view the iframe to begin with unless I refreshed the browser manually...not ideal.
I tried the following:
var hide = () => {
$("#frame").hide();//jQuery
location.reload(true);//javascript
};
Mixing plain Jane javascript with your jQuery should work.
// code where hide (where location.reload was used)function was integrated, below
iFrameInsert = () => {
var file = `Fe1FVoW0Nt4`;
$("#frame").html(`<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/${file}\" frameborder=\"0\" allow=\"autoplay; encrypted-media\" allowfullscreen></iframe><h3>Close Player</h3>`);
$("h3").enter code hereclick(hide);
}
// View Player
$("#id-to-be-clicked").click(iFrameInsert);
All the answers here are good. Since the question specifies about reloading the page with jquery, I just thought adding something more for future readers.
jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML.
~ Wikipedia ~
So you'll understand that the foundation of jquery, or jquery is based on javascript. So going with pure javascript is way better when it comes to simple things.
But if you need a jquery solution, here's one.
$(location).attr('href', '');
There are many ways to reload the current pages, but somehow using those approaches you can see page updated but not with few cache values will be there, so overcome that issue or if you wish to make hard requests then use the below code.
location.reload(true);
//Here, it will make a hard request or reload the current page and clear the cache as well.
location.reload(false); OR location.reload();
//It can be reload the page with cache
You can write it in two ways. 1st is the standard way of reloading the page also called as simple refresh
location.reload(); //simple refresh
And another is called the hard refresh. Here you pass the boolean expression and set it to true. This will reload the page destroying the older cache and displaying the contents from scratch.
location.reload(true);//hard refresh
you may need to use
location.reload()
or also may need to use
location.reload(forceGet)
forceGet is a boolean and optional.
Set this parameter to true if you want to force the browser to take the page from the server to receive rid of the cache as well
Simple Javascript Solution:
location = location;
<button onClick="location = location;">Reload</button>
Probably shortest (12 chars) - use history
history.go()
$(document).on("click", "#refresh_btn", function(event)
{
window.location.replace(window.location.href);
});
It is shortest in JavaScript.
window.location = '';
Y'all may need to use
location.reload(forceGet)
forceGet is a boolean and optional.
The default is false, which reloads the page of the cache.

Categories