I am working on a angular project where I need to track the page loading time.
Is there any method in angular using which I can track page loading time.
Code that I tried:
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart; console.log('Page load time is ' + loadTime);
You can use setInterval combined with angular.element(document).ready().
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script>var time = 0;
var stopwatch = setInterval(function() {
time = time + 0.001;
}, 1);
angular.element(document).ready(function() {
clearInterval(stopwatch);
document.getElementById("text").innerText = "It has taken " + time + " seconds for this page to load.";
});</script>
<span id="text"></span>
Related
not very big on JS.
I currently have a script I use to load/change background images every xxx seconds.
What I would like is to display an image and preload the next one so it displays seamlessly (ie: no jittering or slow loads).
Here is my current script, can this be adapted to achieve such a result?
<!-- Background Image Changer inpired by: https://stackoverflow.com/a/7265145 -->
var images = ['images/image01.jpg',
'images/image02.jpg',
'images/image03.jpg',
'images/image04.jpg',
'images/image05.jpg',
'images/image06.jpg',
'images/image07.jpg',
'images/image08.jpg',
'images/image09.jpg',
'images/image10.jpg',
'images/image11.jpg',
'images/image12.jpg',
'images/image13.jpg',
'images/image14.jpg',
'images/image15.jpg',
'images/image16.jpg',];
var numSeconds = 30;
var curImage = 0;
function switchImage()
{
curImage = (curImage + 1) % images.length
document.body.style.backgroundImage = 'url(' + images[curImage] + ')'
}
window.setInterval(switchImage, numSeconds * 1000);
NOTES: There are 50 images in my script. I've only used fake named placeholders for clarity.
EDIT: To be clear, I only want one image displayed and the next (one) image to be preloaded. It's running on a RPi 3b so not much memory is available.
I want to add a different answer here. There are a few options you can use to improve your web page performance. Using <link> with preconnect and preload rel value can helps you to load resources before using them:
Use preconnect keyword for the rel attribute to tell the browsers that the user is likely to need resources from this origin and therefore it can improve the user experience by preemptively initiating a connection to that origin.
<link rel="preconnect" href="<your-images-base-url">
Use preload keyword for the rel attribute to declare fetch requests in the HTML's , specifying resources that your page will need very soon. This ensures they are available earlier and are less likely to block the page's render, improving performance. Taken from https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/preload
Create preload link:
const preloadLink = document.createElement('link');
document.head.appendChild(preloadLink);
preloadLink.rel = 'preload';
preloadLink.as = 'image';
function preloadNextImage(href) {
preloadLink.href = href;
}
function switchImage()
{
curImage = (curImage + 1) % images.length
document.body.style.backgroundImage = 'url(' + images[curImage] + ')';
preloadNextImage(/* <next-image-url> */)
}
You could just load the next image when displaying the current one using the JavaScript Image object. When switchImages runs again then the image will be already in the browsers cache. Also, the cached images are stored in a new array, so the cache "generator" will be ran only once. With this snippet you will need enough delay between iterations, so the next image will have enough time to be downloaded from the sever.
var images = ['images/image01.jpg',
'images/image02.jpg',
'images/image03.jpg',
'images/image04.jpg',
'images/image05.jpg',
'images/image06.jpg',
'images/image07.jpg',
'images/image08.jpg',
'images/image09.jpg',
'images/image10.jpg',
'images/image11.jpg',
'images/image12.jpg',
'images/image13.jpg',
'images/image14.jpg',
'images/image15.jpg',
'images/image16.jpg',];
var numSeconds = 2;
var curImage = 0;
var cache = [];
function switchImage()
{
curImage = (curImage + 1) % images.length;
document.body.style.backgroundImage = 'url(' + images[curImage] + ')';
if(images[curImage + 1] && !cache[curImage + 1]) {
cache[curImage + 1] = new Image();
cache[curImage + 1].src = images[curImage + 1];
}
}
window.setInterval(switchImage, numSeconds * 1000);
I am trying to create multiple custom javascript audio players on my website but once I copy the code in html the second player does not work, how should I adjust the javascript code for it to work? Here is my code: https://github.com/streamofstream/streamofstream.github.io
and here is relevant part of the code that I am talking about:
index.html relevant part here, I tried to just duplicate this part and change the audio source but once I do this the second player appears but it wont trigger javascript
<script>
function durationchange() {
var duration = $('audio')[0].duration;
if(!isNaN(duration)) {
$('#duration').html(Math.ceil(duration));
}
}
</script>
<div id="audioWrapper">
<audio id="audioPlayer" preload="metadata">
<source src="assets/millriver.wav" type="audio/wav" />
Your browser does not support the audio element.
</audio>
<div id="playPause" class="play"></div>
<div id="trackArtwork"><img src="assets/smiths.jpg" /></div>
<div id="trackArtist">04/28/2021, 8PM Eastern Time, Mill River</div>
<div id="trackTitle">41°20'09.3"N 72°54'37.7"W</div>
<div id="trackProgress">
<div id="elapsedTime"></div>
<input type="range" id="scrubBar" value="0" max="100" />
<div id="remainingTime"></div>
</div>
</div>
<script type="text/javascript" src="js/audioplayer.js"></script>
and java script here (Code by https://github.com/jon-dean/html5-audio-player)
var audioPlayer = document.getElementById('audioPlayer');
var scrubBar = document.getElementById('scrubBar');
var elapsedTime = document.getElementById('elapsedTime');
var remainingTime = document.getElementById('remainingTime');
var playPause = document.getElementById('playPause');
var trackLength;
// Set up a listener so we can get the track data once it's loaded
audioPlayer.addEventListener('loadedmetadata', function() {
// Get the length for the current track
trackLength = Math.round(audioPlayer.duration);
// Set the initial elapsed and remaining times for the track
elapsedTime.innerHTML = formatTrackTime(audioPlayer.currentTime);
remainingTime.innerHTML = '-' + formatTrackTime(trackLength - audioPlayer.currentTime);
});
function runWhenLoaded() { /* read duration etc, this = audio element */ }
// Set up a listener to watch for play / pause and display the correct image
playPause.addEventListener('click', function() {
// Let's check to see if we're already playing
if (audioPlayer.paused) {
// Start playing and switch the class to show the pause button
audioPlayer.play();
playPause.className = 'pause';
} else {
// Pause playing and switch the class to show the play button
audioPlayer.pause();
playPause.className = 'play';
}
});
// Track the elapsed time for the playing audio
audioPlayer.ontimeupdate = function() {
// Update the scrub bar with the elapsed time
scrubBar.value = Math.floor((100 / trackLength) * audioPlayer.currentTime);
// Update the elapsed and remaining time elements
elapsedTime.innerHTML = formatTrackTime(audioPlayer.currentTime);
remainingTime.innerHTML = '-' + formatTrackTime(trackLength - audioPlayer.currentTime + 1);
};
// Set up some listeners for when the user changes the scrub bar time
// by dragging the slider or clicking in the scrub bar progress area
scrubBar.addEventListener('input', function() {
changeTrackCurrentTime();
scrubBar.addEventListener('change', changeTrackCurrentTime);
});
scrubBar.addEventListener('change', function() {
changeTrackCurrentTime();
scrubBar.removeEventListener('input', changeTrackCurrentTime);
});
// Change the track's current time to match the user's selected time
var changeTrackCurrentTime = function() {
audioPlayer.currentTime = Math.floor((scrubBar.value / 100) * trackLength);
};
// Format the time so it shows nicely to the user
function formatTrackTime(timeToFormat) {
var minutes = Math.floor((timeToFormat) / 60);
var seconds = Math.floor(timeToFormat % 60);
seconds = (seconds >= 10) ? seconds : '0' + seconds;
return minutes + ':' + seconds;
}
// Let's reset everything once the track has ended
audioPlayer.addEventListener('ended', function() {
audioPlayer.currentTime = 0;
elapsedTime.innerHTML = formatTrackTime(audioPlayer.currentTime);
remainingTime.innerHTML = '-' + formatTrackTime(trackLength - audioPlayer.currentTime);
playPause.className = 'play';
});
Thank you
I am using the following code in my website which displays the current time
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML =
h + ":" + m;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
i am also using the automatic refresher tag in my html which reloads page after every 60 seconds
<meta http-equiv="refresh" content="60">
what i want is whenever the time changes to next minute the page reloads
which means if current time is 14:05 and when it hits 14:06 the page reloads by reading this time change and NOT by 60 seconds interval from which the user opens the page.
You can set timeout looking at the clock, just get the actual seconds and wait til 60 to reload:
var date = new Date();
setTimeout(function(){
window.location.reload(1);
},(60 - date.getSeconds())*1000)
Just put that at the head inside a script tag
Try using this
setTimeout(function(){
window.location.reload(1);
}, 60000); // 60 sec
Source: How to reload page every 5 second?
or take a look at this too
setTimeout(function(){
var minutes = (new Date()).getMinutes()
if ( !minutes%15 ) location.reload(); // if minutes is a multiple of 15
},60000); // 60.000 milliseconds = 1 minute
Source: jQuery auto refresh page on clock time
Handling the local time using client side script is not recommended because the user's clock might be messed up and thus your system would turn out to be faulty.
So it is better you fetch time from your server using any server-side language like PHP
In PHP:
<?php
echo date("h:i");
?>
Now you can call this function using AJAX and you can easily handle your time.
var result=null;
function getDate(){
var result=$.ajax({
url: "script.php",
type: "POST",
success: function(data){
setTimeOut(function(){getDate();},60000);
}
}).responseText;
}
I want to make a function to change my background <header> every 5 seconds.
On the one hand I have an image that changes every X time, It is generated by a php file:
../bg.php
So I've done that I change the background-image with $("header").css().
Running the script like this:
(function($)
{
$(document).ready(function()
{
var $container = $("header");
$container.css("background-image", "url(bg.php)");
var refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php)");
}, 9000);
});
})(jQuery);
But does not change by itself.
This is just a guess, but there's a good chance that the browser is just caching the file. You could add cache control headers on the server, or else add a nonce parameter each time you change the background:
var counter = 1, refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php?_=" + counter++ + ")");
}, 9000);
It's probably a good idea to go ahead and set the cache headers properly anyway, just to avoid having client browsers needlessly cache the same image over and over again.
Maybe because your browser cache it. place a random number at the end of url:
$container.css("background-image", "url(bg.php?rnd=" + Math.random() + ")");
var refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php?rnd=" + Math.random() + ")");
}, 9000);
window.setInterval(function(){
/// call your function here
}, 5000);
You probably need to call location.reload(); as well.
Try to add query to bg.php
var d = new Date();
var n = d.getTime();
$container.css("background-image", "url(bg.php?" + n + ")");
the browser will not load the file with same name again
You're going to need to set the background-image to a different URL if you don't want to reload the entire page. However, you can attach a fragment (ex. http://example.com/index.php#fragment), or alternatively a query string (ex. http://example.com/index.php?querystring) to that URL .php file each time. If you are going to reset it every 5 seconds, a good method would be to append a new Date().getTime(); to the end of the image source URL, like this:
var currentDate = new Date();
$container.css("background-image", "url(bg.php#" + currentDate.getTime() + ")");
or even more succinctly/efficiently
$container.css("background-image", "url(bg.php#" + new Date().getTime() + ")");
You should end up with a background-image property of something like url(bg.php#1413320228120). This is good because the fragment won't affect where the browser looks for the image (still bg.php), but it'll consider it a different URL each time and load it again.
Your solution should look something like:
(function($)
{
$(document).ready(function()
{
var $container = $("header");
$container.css("background-image", "url(bg.php)");
var refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php)");
}, 9000);
});
})(jQuery);
I'm trying to display a progress bar on a html page using javascript. However,
when the browser tab containing the code becomes inactive, the progress bar stops updating,
being resumed when the tab is active again.
How can I prevent the browser from stopping/pausing the execution of javascript code when the window is inactive?
Although it may be irrelevant, here is the code:
Object.progressBar = function(){
$( "#question-progress-bar" ).progressbar({
value: false,
complete: function(event, ui) { ... }
});
var seconds = 15.0,
progressbar = $("#question-progress-bar"),
progressbarValue = progressbar.find(".ui-progressbar-value");
progressbarValue.css({
"background": '#c5b100',
"opacity" : '0.8'
})
var int = setInterval(function() {
var percent = (15-seconds)/15*100;
seconds=seconds-0.1;
progressbar.progressbar( "option", {
value: Math.ceil(percent)
});
$("#question-progress-bar-seconds").html((seconds).toFixed(1)+"s");
if (seconds <= 0.1) {
clearInterval(int);
}
}, 100);
}
Instead of using setInterval and assuming a certain amount of time has passed between calls (even when it's up front, setInterval has hit or miss accuracy) use the Date object to get a time when the bar starts, and compare that to the current time at each iteration.
<html>
<head>
<script>
function go()
{
var pb = new ProgressBar(5, "targ");
}
window.onload = go;
function ProgressBar(l, t)
{
var start = Date.now();
var length = l * 1000;
var targ = document.getElementById(t);
var it = window.setInterval(interval, 10);
function interval()
{
var p = 100 * (Date.now() - start) / length;
if(p > 100)
{
p = 100;
window.clearInterval(it);
alert("DONE"); // alternatively send an AJAX request here to alert the server
}
targ.value = (Math.round(p) + "%");
}
}
</script>
</head>
<body>
<input type="text" id="targ" />
</body>
</html>
I've made an example object, here, that immediately starts a countdown when instantiated and calls an alert and kills the interval timer when done. Alternatively an AJAX call, or any other sort of call can be done upon completion.
It should be noted that this will NOT complete the call if the browser stops Javascript all together. It will, however, complete it as soon as the tab has been given focus again if enough time has passed in the interim. There is no way for a website to alter this sort of browser behavior from the scripting side.
Hope that helps!