Prevent static files inside a CSS from being displayed before the page is loaded - html

I am modifying some JSP files, and every time I upload a new version, if people don't update the cache, the styles are not rendered as they should be; it is looking not good and without styles applied.
To solve this problem, I have followed an example from Stack Overflow that adds a numeric value to the CSS file, preventing it from being cached in the browser. The specific link I've seen is this one:
https://wpreset.com/force-reload-cached-css/
But I've found that whenever I press F5 or navigate to other JSP's that apply the same stylesheet, the files that are part of that CSS file are always seen just before rendering. I added a GIF with a dummy example to exhibit what I mean:
Animated GIF demonstrating the problem
How could I avoid this?

Would something like the following help?
/* CSS */
.no-js #loader { display: none; }
.js #loader { display: block; position: absolute; left: 100px; top: 0; }
|
// Js
$(window).load(function() { // Wait for window load
// Animate loader off screen
$("#loader").animate({
top: -200
}, 1500);
});
Like it is used here.

I have already been able to solve it.
In the end I have chosen to nest inside a window.onload, the document.ready like this:
window.onload = function () {
document.getElementsByTagName("html")[0].style.visibility = "visible";
var h, a, f;
a = document.getElementsByTagName('link');
for (h = 0; h < a.length; h++) {
f = a[h];
if (f.rel.toLowerCase().match(/stylesheet/) && f.href && f.href.indexOf("custom-common.css") != -1) {
var g = f.href.replace(/(&|\?)rnd=\d+/, '');
f.href = g + (g.match(/\?/) ? '&' : '?');
f.href += 'rnd=' + (new Date().valueOf());
}
}
$(document).ready(function () {
$('.main-link').click(function () {
And change the visibility of the html document. I have omitted the rest of the code, but you can get an idea. Many thanks to Robert Bradley and Adam for shedding light and helping me.

Related

Text in hyperlink HTML

I'm modifing an existing script to genearte an HTML file. Script puts a location (system path) under a hyperlink. But when I try to copy it from the html file, I get additional "https://" at the front of the text.
As example I see this printed in .html file
<td> ERROR massage. Please find the log here </td>
But when I do a right click -> copy link address from chrome I get this:
https://home/user/log
I'm not a web developer, so dont know if I use correct tags to get the job done. So, how can I get exactly the text I need?
Thanks
Probably a very farfetched solution, but in case you want to copy to clipboard the exact value of the href attribute of an anchor element, regardless of any uri schema where the page is getting loaded from and ignoring upfront the fact that probably such url should be encoded as file:// since it's clearly a filesystem path anyway,
a strategy to adopt could be to have an event triggering the appearence of an overlay that will show such information on top of the whole document and that will expect the click of the close button to return to the previous state.
The problem is that it's quite temerarious to change the clipboard data programmatically since there are security rules engaged that depends on too many conditions that we want to ignore here.
So all you would need to do if you are interested to such strategy, would be to add this code somewhere at the end of your document inside a <script> tag (and as long as js will be allowed to run in your page).
Here you have to hold the CTRL key while clicking the link, and an overlay will showup echoing the exact value coming from the href attribute of the link clicked. So that you can just copy by yourself in the clipboard. Of course you have to give focus to the document before trying to hold the CTRL key.
let ctrlKeyPressed = false;
document.querySelectorAll('a')
.forEach(anchor => {
anchor.addEventListener('click', e => {
if(ctrlKeyPressed){
e.preventDefault();
const overlay = document.createElement('div');
overlay.classList.add('overlay');
const container = document.createElement('div');
const urlSpan = document.createElement('span');
urlSpan.innerText = e.target.getAttribute('href');
container.appendChild(urlSpan);
container.innerHTML += '<br>';
const close = document.createElement('a');
close.innerText = 'close';
close.href = "#";
container.appendChild(close);
close.addEventListener('click', event=>{
event.target.closest('.overlay').remove();
});
overlay.appendChild(container);
document.body.appendChild(overlay);
}
});
});
document.addEventListener('keydown', e => {
if (e.ctrlKey && !ctrlKeyPressed){
ctrlKeyPressed = true;
console.log('holding ctrl key');
}
});
document.addEventListener('keyup', e => {
if (ctrlKeyPressed){
ctrlKeyPressed = false;
console.log('left ctrl key');
}
});
.overlay{
position: fixed;
display: flex;
justify-content: center;
left:0;
top:0;
width: 100%;
height: 100%;
z-index: 1;
border: solid black;
background: white;
font-size: 30px;
align-items: center;
}
.overlay > div {
text-align: center;
}
<td> ERROR massage. Please find the log here </td>

Change background dependent upon arriving URL

Hi and hope someone can help.
I have a live site and also a development site where I test out new code before deployment but basically they have the same content e.g.
Live = www.myserver.com/live/index.html
Development = www.myserver.com/development/index.html
Is there a way of setting the (say) CSS background property dependent upon the url that has been used to arrive at the site.
My current CSS =
body {
background: #eff;
/* change this to background: #ccc; if on development site */
margin:25px;
}
Why?
Well, I frequently find myself uploading or testing new code on the wrong site.
Not a big issue I know but useful if I could have a visual clue as to which site I'm testing.
My thanks for your interest.
Now Solved Thanks for input from #Adam Buchanan Smith, #Dekel and Mr Green.
I sort of used #Dekel's logic but changed it to jQuery along the following lines:
<script>
$(document).ready(function(){
// Set background dependent upon url i.e. www.myserver.com/cab or www.myserver.com/cab2
// cab2 is the development site, cab the live site
// Also change text in div id="live" from 'Live Site' to 'Development Site' if arrives at by cab2
if (document.location.pathname.indexOf('cab2') > -1){
$('body').css({"background":"#BFFFDF"});
document.getElementById('live').innerHTML = "Development Site";
} else {
$('body').css({"background":"#efffff"});
document.getElementById('live').innerHTML = "Live Site";
}
}
</script>
My thanks to all for your interest!
Not something you can do in pure html/css, but you can use both javascript and server side language for that.
In javascript you can check if the document.location.hostname or document.location.pathname to check the domain/url you are currently using.
In javascript for example you can use:
if (document.location.pathname.indexOf('development') > -1) {
body = document.getElementsByTagName('body')[0]
body.setAttribute('class', body.getAttribute('class') + ' development')
}
Using PHP you can use $_SERVER['REMOTE_HOST'] and $_SERVER['REQUEST_URI'].
if (strpos($_SERVER['REQUEST_URI'], 'development')) {
echo "<body class=\"development\">";
} else {
echo "<body>";
}
And in the css file you can use:
body {
background: #eff;
}
body.development {
background: #ccc;
}
Theoretically something like this could work for you in just plain javascript using document.referrer;
<body onload="checkURL()">
</body>
<script>
function checkURL(){
var testPage = "www.testpage.com";
var livePage = "www.livepage.com";
var lastPage = document.referrer;
if (lastPage == livePage){
//do something here
}
else if {lastPage == testPage}
//do something else
}
else{
//umm what did you do?
}
</script>

Disconnect between adding a class and CSS getting applied [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm having some annoying issues between Bootstrap/JQuery/my own CSS, tell me if this sounds like a problem you know how to fix.
I'm implementing my own "slider", with AJAX calls loading content onto the page depending on the navigation the user does. The problem comes in with my navbar. When an onhashchange event happens, I'm loading the correct content in, clearing the active class from the <li> element, and re-adding the active class to the appropriate <li> element.
Unfortunately, setting the active class isn't causing the appropriate CSS I have written to be applied, a slight darkening. There could be a million things causing THAT, I realize. But hardcoding an active class gives exactly the desired result. I don't know where the disconnect is. I ask myself, is a page loading problem getting in the way of the CSS being applied? I don't know.
Thanks in advance.
HTML:
...
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="sections nav navbar-nav">
<li>Call</li>
<li>Police</li>
<li>Charges</li>
<li>Jail</li>
<li>Courts</li>
<li>Resources</li>
</ul>
...
</div>
...
My CSS:
.navbar {
background-color: #231f20;
}
.navbar .sections>li>a:hover {
background-color: #4f4c4d;
}
/* Overriding */
.navbar a { color: #DDD !important; }
.navbar a:hover { color: #AAA !important; }
.navbar-nav>.active>a { background-color: #4f4c4d !important; }
My JS:
/* Constants */
var elem = $('.sections li a');
var pages = [];
for(i=0; i<elem.length; i++) {
//console.log(elem[i])
pages[i] = elem[i].hash;
}
var first = 0;
var last = pages.length;
...
function loadPage(hash, callback) {
/* Loads the content inside the "#main" element on the
page found at <url> into the "#main" element of the
current page. Then sets the links and buttons
accordingly. */
url = hash.split('#')[1] + '.html'
$('#main').load(url + "#main", callback);
setLinks(hash);
}
function setLinks(hash) {
for (i=0; i<=last; i++) {
if (pages[i] == hash) {
page_num = i;
}
}
var previous = page_num - 1;
var next = page_num + 1;
...
$('.sections li').removeClass('active');
$('.sections li').eq(page_num).addClass('active');
}
$(document).ready(function() {
...
$(window).on('hashchange', function() {
loadPage(window.location.hash);
});
});
You should make use of the callback functionality offered in the function loadpage. You are doing an asynchronic call, and directly applying the css. However, the page has not been updated yet (it takes some time). You should do something like this (only the updated functions):
function loadPage(hash, callback) {
/* Loads the content inside the "#main" element on the
page found at <url> into the "#main" element of the
current page. Then sets the links and buttons
accordingly. */
url = hash.split('#')[1] + '.html'
$('#main').load(url + "#main", callback);
// setLinks(hash); <-- don't do this, it will be executed to early!
}
$(document).ready(function() {
...
$(window).on('hashchange', function() {
loadPage(window.location.hash, setLinks); // <-- making use of the callback functionality
});
});
And remove the setLinks call from the loadPage function itself. By passing it in as the callback function, it will get executed once the $('#main').load is finished.

Prevent images from being downloaded to page on mobile site

How can I make it so that within the mobile version of my site the images are not downloaded to from the web server as these are large files that are not needed and not being used and therefore severely impacting the use of the mobile version of the site. Having looking at previous threads of such nature I saw that hiding the parent of the image using code such as below can benefit.
.parent {display:block;}
.background {background-image:url(myimage.png);}
#media only screen and (max-width:480px) {
.parent {display:none;}
}
The problem being I don't want to use background image CSS for SEO issues associated with them as I like to use Schema tagging etc ..so how can I prevent an IMG tag from being downloaded, as display:none; only hides the image rather than stopping it being downloaded.
Note: This is not for copyright protection issues e.g. preventing right click etc etc but for speed and ultimately size of the downloaded content to mobile.
This solution uses CSS to prevent background-images from loading and jQuery to prevent images from loading. I'm not familiar with any CSS solution that will prevent images from loading.
JS Fiddle: http://jsfiddle.net/CoryDanielson/rLKuE/6/
If you know the images height and width (or even ratio) ahead of time you could set the background-image for a bunch of fixed size DIVs. This might be applicable for icons and layout-type images. Look at the HTML/CSS below for an example of that.
Background Images
/* hidden by default */
aside {
display: none;
}
/* Pictures load for 'big screen' users.. pcs/tablets? */
#media screen and (min-width: 750px) {
aside {
display: block;
}
.catpicDiv {
height: 100px;
width: 100px;
display: inline-block;
border: 1px solid red;
background-image: url('http://img2.timeinc.net/health/images/slides/poodle-1-400x400.jpg');
background-size: cover;
}
}
and HTML
<aside>
<div class="catpicDiv"></div>
<div class="catpicDiv"></div>
<div class="catpicDiv"></div>
</aside>
Image Elements are a different story...
I don't know of any purely CSS solution to prevent them from loading the images. So I'd solve it like this:
Define IMG tags as follows
<img src="" data-src="url-to-image.jpg" />
Then, somewhere in the head of the document you need similar javascript
1) Function to load all of the images
function loadAllTheImages() {
$("img").each(function(){
$(this).attr('src', $(this).attr('data-src'));
});
}
2) Code to determine if the user is on mobile or a PC (slow vs fast connection) and then load the images.
This code isn't bulletproof, there are much more accurate and reasonable tests than this.
$(window).load(function(){
if ( $(window).width() > 750 ) {
loadAllTheImages(); // !
} else {
$("body").append("<a id='mobileCheck' href='javascript: void(0);'>I GOTS 4G, LEMME HAVE EM!</a>");
}
});
3) As well as maybe some code to activate a button to load the images anyways? Why not, I guess... ?
$(document).ready(function(){
$('body').prepend("<h1>" + $(window).width().toString() + "</h1>");
$('body').on('click', '#mobileCheck', function(){
loadAllTheImages(); // !
$("#mobileCheck").remove();
});
});
Similar solution as here and what I hypothesized in the comments:
Delay image loading with jQuery
There is no native solution in CSS that would prevent images from loading even if you hide them or set display to none.
You have to use some JS to achieve that result. If you are familiar with JS that should not be an issue at all. There are several plugins ready to go to do what you want. You can also write your own JS because its not that difficult.
Here is my code that loads images based on the screen size:
DEMO AT CODE PEN
It works without any libraries like JQ but if you use one of those it will automatically switch to it (Tweak it to your specific needs).
JS
// use jQuery or pure JS
if (typeof jQuery !== 'undefined') {
// jQuery way
// alert("jquery");
$(function() {
$(window).on('load resize', function() {
var products = $("[data-product-image]");
products.each(function(key, value) {
var bg = null;
if (window.outerWidth < 500) return;
if (window.outerWidth < 1000) bg = $(value).data("product-image-s");
if (window.outerWidth >= 1000) bg = $(value).data("product-image");
console.log($(window).outerWidth);
$(value).css({
'background-image': 'url(' + bg + ')',
'background-position': 'center',
'background-size': 'cover',
});
});
});
});
} else {
// Pure JS way
// alert("JS");
(function() {
window.addEventListener('load', wlImageLoader);
window.addEventListener('resize', wlImageLoader);
function wlImageLoader() {
console.log('event! Trig trig');
var all = document.getElementsByTagName("div");
var products = [];
for (i = 0; i < all.length; i++) {
if (all[i].hasAttribute('data-product-image')) {
products.push(all[i]);
}
}
Array.prototype.forEach.call(products, function(value) {
var bg = null;
var curent = window.getComputedStyle(value).getPropertyValue('background-image');
console.log(curent);
if (window.outerWidth < 500 || curent != 'none') return;
if (window.outerWidth < 1000 && curent == 'none') bg = value.getAttribute('data-product-image-s');
if (window.outerWidth >= 1000 && curent == 'none') bg = value.getAttribute('data-product-image');
// if (window.outerWidth >= 2000 && curent == null) bg = value.getAttribute('data-product-image-l');
if(bg == null || curent != 'none') return;
value.style.backgroundImage = "url(" + bg + ")";
value.style.backgroundPosition = "center";
value.style.backgroundSize = "cover";
curent = window.getComputedStyle(value).getPropertyValue('background-image');
console.log(curent);
});
}
})();
}
HTML
<div data-product-image="img/something_normal.jpg" data-product-image-s="img/something_small.jpg" id="p3" class="product">
However if you are a time loading freak you probably prefer to write your code natively in JS as you often don't use most of the jQuery library. For fast internet connection this is not a problem but if you target mobile devices on country side that might make a difference.
I would suggest combining perhaps the #import and #media commands to only #import the stylesheet which contains images if the #media tag meets you criteria (say, over a certain resolution).
So by default you wouldn't import the stylesheet which applies the BG image, you'd only end up doing it if you had determined the site was 'non-mobile'..if that makes sense!
The W3c site has some decent examples of combining the rules:
http://www.w3.org/TR/css3-mediaqueries/#media0

How to disable a CSS class with javascript on window.load()

I want to disable a CSS class when the page loads. I have the class .rtsULmenuLeft:
.rtsULmenuLeft
{
list-style:none;
margin: 0;
padding: 0;
}
All instances of the style need to be disabled. How can I do this?
In ListStyle Image iam using custom image. It is displaying and again hidden at last. That is, with bullet marks it is displaying again. I need to have that custom image to be present. Thanks.
Here is a working example of what you have requested: http://jsfiddle.net/ALLew/
In the example:
all ULs are yelow
items with class rtsULmenuLeft are red
items with class rtsULmenuRight are blue
As you can see, the rtsULmenuLeft classNames are removed, and the lists are displayed yellow.
// Define a function to run on page load.
var loadCheck = function() {
// Cancel the function if the page isn't loaded...
if(document.readyState !== "complete") {
// ... but call it again in 100 milliseconds.
setTimeout(loadCheck, 100);
return;
}
// From here on, the page is loaded.
// Obtain a list of all elements with the particular class name
var elList = document.getElementsByClassName("rtsULmenuLeft");
// Loop over the elements until there are no longer any with the class.
while(elList.length > 0) {
// For each element, remove the class.
elList[0].className = elList[0].className.replace(
/\brtsULmenuLeft\b/, // RegExp of class name in word boundaries
"" // Replace with empty string - remove it.
);
}
};
loadCheck();
​
Using jquery:
$('.rtsULmenuLeft').removeClass('rtsULmenuLeft');
Add display:none
.rtsULmenuLeft
{
list-style:none;
margin: 0;
padding: 0;
display:none
}