Website changes are caching and will not update for clients - javascript

I have made some changes on a live website (I know, not the best practice, but I was told to) and I'm having issues with caching. Every time I make a change to our CSS (SASS actually), I have to hit CTRL F5 to see the changes. That's not a problem for me, but the users are starting to complain of a broken website and many of them don't know how to clear the cache or use CTRL F5.
I have tried adding the following code, but it's not working.
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
I have also tried adding this script:
<script type="text/javascript">
$(document).ready(function(){
$('img').each(function(){
var date = new Date;
// add the current unix timestamp in microseconds to the the image src as a query string
this.src = this.src + '?' + date.getTime();
});
});
</script>
I don't know Javascript though, so I don't know how to use it properly. I have searched for answers and other people have said these things work for them, but they simply are NOT working for me. I am a designer and front-end developer, so PHP and Javascript are a bit beyond me.
Finally, I've also read about using version tags - ?v=x.x, but my issue is the site was coded by other developers and I have no clue how they are linking to our stylesheet (using SASS).
Any help would be great appreciated!
Thanks!

Ideally you'd use PHP to check the file's filemtime() (the time it was last modified), and use a technique called versioning to indicate it's a changed file, and to not load it from cache.
The resulting HTML would look something similar to this:
<link href="/your/css/file.css?ver=<?php echo filemtime('/your/css/file.css'); ?>" rel="stylesheet" type="text/css"/>

Call the external CSS file adding a random code as GET variable in PHP.
Something like this:
<script src="yourfileUpdated.css?<?php echo rand() ?> rel="stylesheet" type="text/css" />

Styles are added with wp_enqueue_style function. Search your theme, it is probably in functions.php.
Then use like this:
wp_enqueue_style('main-styles', get_template_directory_uri() . '/css/style.css', array(), filemtime(get_template_directory() . '/css/style.css'), false);
Read more here https://wordimpress.com/wordpress-css-and-js-cache-busting/.

Related

Load TXT file - Refresh the contents

It's been a while since I tried my hand at HTML - and I'm getting stumped - hopefully someone can come to my aid.
My goal: On my LOGIN page, I want to add an "outage" notification section. I don't want the admins to access the login.html file; I want the data to be grabbed from a text file.
My attempt: I created an "outage.txt" file which is scheduled to update the webserver every morning. I then use a DIV and OBJ to load the "outage.txt" file. This does work.
<table><tr><td>
<div id="outage"><object width=475 data="outage.txt"></object></div>
</td></tr></table>
My problem: When I update my "outage.txt" file and refresh the page, the data is NOT reflected on the page. The only way I can get it to load correctly is to do a force-refresh (ctrl-F5).
What I tried:
-) I added meta data to not use cache. But it still does not update my data.
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
-) I've changed my txt pull to JQUERY. It pulls the data nicely - but still does not update it.
$.get( "outage.txt", function( data ) {
Need help: At this point I'm not sure what to ask help for. Is there a better way to grab a text file and display it on the page? How to I ensure that the page is being correctly loaded and not pulled from cache. Is there a way to FORCE the page to force-refresh?
When I do a refresh (Ctl-R) on my Chrome, it updates the text.
Try:
window.onload = function() {
document.getElementById("objid").data = "outage.txt";
}
<object id="objid" width=475 data="outage.txt">
I have my answer and will do my best to summarize it here.
Looks like the browser sees the data="outage.txt" file and says 'Hey! I already have this in cache, no need to grab a file again'. The trick is to force a change to the filename which tells the browser that 'This is a new file, please load it no matter what'.
<div id="outage"><object id="outageid" width=475></object></div>
<script type="text/javascript">
document.getElementById("outageid").data = "outage.txt?" + Math.floor(Math.random() * 100);
</script>

JS and CSS not loading in html

I've been following this article (https://dev.to/programliftoff/create-a-basic-webpage-with-css-and-javascript--104i) to get started on building an interactive webpage, but I can't get the JS and CSS to work.
I'm working in Sublime, and I followed this tutorial (https://www.youtube.com/watch?v=oqD5C77Tk3I&feature=youtu.be) to run it through http rather than the file system.
I've double checked the folder paths fifty times (they're just saved on my desktop as 'scripts' and 'styles' in the same folder as my index.html doc), and tried different variations of dots at the start of the paths and slashes both ways, but the JS and CSS just won't load. I've also moved the 'link rel' and 'scripts async src' lines between the head and body tags, but it doesn't seem to make a difference.
My html doc looks like this,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Website</title>
<link rel=“stylesheet” type="text/css" href=“../styles/styles.css” />
<script async src="./scripts/index.js"></script>
</head>
<body>
<h1>Hello, World</h1>
<h4 id=‘date’></h4>
<img src="images/IMG_4945.jpg" alt="My test image">
</html>
My JS doc looks like this,
document.getElementById('date').innerHTML = new Date().toDateString();
My CSS doc looks like this,
body {
text-align: center;
background-color: #ffe6e6;
}
Hard to tell without looking at your file structure, but let's assume you have it like this:
|-Project
|-----css
|---------style.css
|-----js
|---------main.js
|-----index.html
in your index.html you should be calling your css like this:
<link rel="stylesheet" href="/css/style.css" />
in UNIX based OS's (and localhost Windows) / equates to document root. It's best to do this as you're guranteed to always call that file no matter where you copy + paste code to.
Note: In Windows servers / doesn't work - not sure why. Windows just sucks I guess.
Remove the async keyword from your script element. That isn't an asynchronous script and it modifies the DOM before it's ready.
Use jQuery $(document).ready(function() {}); or JS window.onload = function() {}; and remove that async attribute so your script is run in synch with the DOM.
In other words, you cannot edit the document before it has been created. But you are trying to do that with an async and no check for if the document is ready.
../ means parent folder. So:
<link rel="stylesheet" type="text/css" href="styles/styles.css" />
<script src="scripts/index.js"></script>
Double quotation marks in your code are valid? “ -> " Pls check it.

Embed markdown (md) into HTML

I need help embedding a markdown, or *.md, file inside of an HTML index file. I have found that I can embed HTML inside of markdown, but not vice-versa. This would help to increase the speed of my editing because markdown format is extremely easy to use, (as I'm using it now) and I don't have to change the format of the rest of my site. I know that something like this is done to embed another HTML file with <iframe src="path/to/html>html-name</iframe>. I could also use javascript to interpret the md format on page load. Thanks ahead of time.
Here's the solution that I have long since forgotten about:
Forgetting that I asked this question and getting no answers, I created my own solution as an extension off of Chris Jeffrey's marked.js.
I call it tagdown.js.
Here it is: http://spikespaz.com/tagdownjs/
Just in case that link, or my domain, expires: https://spikespaz.github.io/tagdownjs/
Github: https://github.com/spikespaz/tagdownjs
This allows markdown to be added directly to the site, within a tag set with the class markdown. See the example on the site. There is no theme system in it, it's just the markdown parser.
Update
The project, TagdownJS, has been deleted from Github. The code for it seems so simple that it doesn't deserve its own repository.
Until it finds a new home, just go find Christopher Jeffery's Marked.js, and use this following code with it.
document.body.style.display = "none"; // Hide the page until it's finished rendering.
document.createElement("markdown");
var md_tags = document.getElementsByTagName("markdown"); // Returns array of all markdown tags.
for (var i = 0; i < md_tags.length; i++) { // Iterate through all the tags, and generate the HTML.
var md_text = md_tags[i].textContent.replace(/^[^\S\n]+/mg, ""); // I love regex, so shoot me.
var md_div = document.createElement("div"); // Make a new div to replace the fake tag.
md_div.id = "content";
md_div.innerHTML = marked(md_text);
md_tags[i].parentNode.appendChild(md_div); // Add remove the old raw markdown.
md_tags[i].parentNode.removeChild(md_tags[i]);
}
document.body.style.display = ""; // Show the rendered page.
https://github.com/zhlicen/md.htm An example of zeromd.js Just serve the md.htm file and md files, and visit directly by url:
/md.htm?src=README.md
Live demo: https://b.0-0.plus/blog/md.htm?src=https://raw.githubusercontent.com/microsoft/vscode/main/README.md
Basicly, you need to interpret MD format into HTML. Javascript is an option.
Take below as an example. (Though Windows, independent of OS)
Let's say a folder mytest looks like,
D:\mytest>dir
Volume in drive D is Data
Volume Serial Number is ABCD-EFGH
Directory of D:\mytest
12/03/2020 10:10 AM <DIR> .
12/03/2020 10:10 AM <DIR> ..
12/03/2020 10:09 AM 7,973 example-image.jpg
12/03/2020 10:12 AM 4,619 md_html.html
12/03/2020 10:00 AM 2,299 md_html.min.js
3 File(s) 14,891 bytes
2 Dir(s) 778,204,147,712 bytes free
D:\mytest>
Here is the html content,
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link rel="stylesheet" href="https://cdn.bootcss.com/highlight.js/9.12.0/styles/atom-one-light.min.css" />
<link rel="stylesheet" href="https://cdn.bootcss.com/github-markdown-css/2.8.0/github-markdown.min.css" />
<title>Marked In HTML</title>
</head>
<body>
<template type="markdown">
Try Marked In HTML !
====
</template>
</body>
<script src="https://cdn.bootcss.com/marked/0.3.6/marked.min.js" charset="utf-8"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.12.0/highlight.min.js" charset="utf-8"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.12.0/languages/javascript.min.js" charset="utf-8"></script>
<script src="md_html.min.js" charset="utf-8"></script>
<script type="text/javascript">
markedInHtml.init()
</script>
</html>
And the js,
!function(n){function t(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return n[r].call(i.exports,i,i.exports,t),i.l=!0,i.exports}var e={};t.m=n,t.c=e,t.i=function(n){return n},t.d=function(n,e,r){t.o(n,e)||Object.defineProperty(n,e,{configurable:!1,enumerable:!0,get:r})},t.n=function(n){var e=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(e,"a",e),e},t.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},t.p="",t(t.s=1)}([function(n,t,e){"use strict";function r(n){return n&&n.__esModule?n:{default:n}}function i(n){if(Array.isArray(n)){for(var t=0,e=Array(n.length);t<n.length;t++)e[t]=n[t];return e}return Array.from(n)}function a(n,t){if(!(n instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0}),t.MarkedInHtml=void 0;var o=function(){function n(n,t){for(var e=0;e<t.length;e++){var r=t[e];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(n,r.key,r)}}return function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t}}(),u=e(3),l=r(u),s=e(2),c=r(s);t.MarkedInHtml=function(){function n(){a(this,n),l.default.setOptions(this.options||{gfm:!0,tables:!0,breaks:!1,pedantic:!1,sanitize:!1,smartLists:!0,smartypants:!1,highlight:function(n,t,e){return c.default.highlightAuto(n).value}})}return o(n,[{key:"init",value:function(){var n=this;document.querySelectorAll('template[type="markdown"]').forEach(function(t){var e=document.createElement("div");e.innerHTML=n.parse(t),e.id=t.id,e.classList.add(["markdown-body"].concat(i(Array.from(t.classList)))),e.dataset.markdown=n.intelligentProcessingIndent(t),t.parentElement.replaceChild(e,t)})}},{key:"parse",value:function(n){return(0,l.default)(this.intelligentProcessingIndent(n))}},{key:"intelligentProcessingIndent",value:function(n){var t=n.innerHTML.split("\n");t.length&&/^\s*$/.test(t[0])&&t.shift(),t.length&&/^\s*$/.test(t[t.length-1])&&t.pop();var e=Math.min.apply(Math,i(t.map(function(n){return n.length?n.match(/^\s*/)[0].length:1/0})));return t.map(function(n){return n.substring(e)}).join("\n")}}]),n}()},function(n,t,e){"use strict";var r=e(0);window&&(window.markedInHtml=new r.MarkedInHtml)},function(n,t){n.exports=hljs},function(n,t){n.exports=marked}]);
And the jpg,
After open the html, you should be able to convert
Try Marked In HTML !
====
into
You can try to replace the template, some effect may not be able to present. For example, use quick markdown example by John Gabriele, the equation are not shown well.
Someone, like 🎅 would suggest to use snippet, yet I failed to get that ❄️ work, parsing not successful. 🥺

trying to get the jquery Datepicker to function

I can't seem to get this working altho it is all on the website. I am not any good at js so that doesn't help either to be honest.
so I have basically done exactly the same as what they have on their website but just doesn't seem to function.
Signup open:<br><input type="text" name="reg_start" class="datepicker" value=""/><br>
Signup closed:<br><input type="text" name="reg_end" class="datepicker" value=""/><br>
This is there code what is the same as mine
<script language="javascript" src="protoplasm.js"></script>
<script language="javascript">
// transform() calls can be chained together
Protoplasm.use('datepicker')
.transform('input.datepicker')
.transform('input.datepicker_es', { 'locale': 'es_AR' });
</script>
Here are the includes I am doing
<link rel="stylesheet" href="jquery/datepicker/datepicker.css">
<script src="jquery/protoplasm.js"></script>
<script src="jquery/datepicker/datepicker_src.js"></script>
<script src="jquery/datepicker/datepicker.js"></script>
Here is the website I got the datepicker from
http://jongsma.org/software/protoplasm/control/datepicker
I understand that in their code they do not have the extra src includes but I put these in when I have been trying to get it working. I left them in the code as I think I will need to include them but not 100% as once again js isn't my strongest point because I am new to coding and need to get a lot more learning in js.
If anyone could help me out on how to get this working that would be great and I would appreciate any sort of help that you may be able to provide.
Thanks for reading
I managed to solve this problem I was having. What I done was I ended up putting the datepickers into .php file and then included it into my form. I added the js and css includes into this file as well and everything seems to work.
below I have included the link to the timepick I used and also my form, php include and the php what is needed to sort the date before sending to the database. If anyone finds this answer useful then please hit the +1 button.
Below is the link to jquery where I got the date and time picker from. The version I downloaded was 2.1.8 and you should be able to see the download button in right corner and it is a orange button.
http://plugins.jquery.com/datetimepicker/
Below is the .php file. I called it regend.php all of the jquery and css is included in the link above.
<link rel="stylesheet" type="text/css" href="jquery/master/jquery.datetimepicker.css"/>
<input type="text" value="date/time" id="regend" name="reg_end"/>
<script src="jquery/master/jquery.js"></script>
<script src="jquery/master/jquery.datetimepicker.js"></script>
<script>
$('#regend').datetimepicker();
$('#regend').datetimepicker({value:'date/time',step:10});
</script>
Below is the include that I added to my form. I added this within <form>.......</form>. I added it to the location I wished it to be displayed.
Signup close:<?php include("indexmodules/regend.php");?><br><br>
Below is the php code that I used before i sent it to the database to be saved.
$reg_end = preg_replace('#[^0-9]#i', '', $_POST ['reg_end']);
$unix_time = strtotime($reg_end);
$date2 = date("Y-m-d H:i:s",$unix_time);
All of the above code should help out any new beginner who is trying to get a date picker working on their website. If I enhance this code I will also post the updated version or version below this.
Thank you to the guys who commented on my original post and I hope this helps people out in the future.

Add random number to .css so it doesn't cache

I'm trying to get the styles.css to not cache as the server is having issues with the css when it caches.
<script>
var numBAH = Math.floor(Math.random()*100);
</script>
<link href="styles.css+ numBAH +" rel="stylesheet" type="text/css" />
You can do this in the head of your document :
<script>
document.write('<link href="styles.css?r='+ Math.floor(Math.random()*100) +'" rel="stylesheet" type="text/css" />');
</script>
BUT :
you have great probabilities of finding two times the same number
you shouldn't generally avoid caching
Solutions I propose :
1) use (new Date()).getTime() instead of a random number
2) simply change the number when the version changes : styles.css?v=3 (without javascript)
If you have access to a server-side language it would be neater to render the link tag with a query string that is a hash of the entire content of the file. In that way, the cache invalidator ey will change only when the content of the file has actually changed.
After having seen the discussion that has followed, about how you never want to use cache, because it loads too quickly, I want to change my answer. Not to new Date(), but to: fix your page so that loading quickly is a desired result. If you're having specific problems with that, create a question that targets those problems, don't go directly for the lousy workaround.
Cache busting can be work without server-side rendering.
I tested recent versions of firefox, chrome and safari in both mobile and desktop, this code worked. (I'm Not sure about IE, though..)
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var numBAH = Math.floor(Math.random()*10000);
document.write('<LI' + 'NK HREF="./path/to/style.css?cacheBusting='+numBAH+'" rel="stylesheet">');
</SCRIPT>
</HEAD>

Categories

Resources