update page content automatically

Asked

Viewed 712 times

3

How can I display in the browser changes made to the stylesheet without using the meta tag refresh? This is only possible using javascript?

  • 1

    Yes, it is only possible with Javascript (because it is necessary to reload the style sheets).

  • You’re looking for something like the Browsersync? Every time you make a change to HTML, CSS or Javascript the page will update and reflect the changes.

1 answer

3


if you want the modifications made to the css files to be automatically reflected on the page, I find it difficult unless you find a way to notify the browser that a new version of CSS is available.

you could even try to make a manual control, where all your files css would have an add on the link stating the latest version, type arquivo.css?versao=3 and whenever you include a new version on the server, the same would notify the browser using a websocket.

If all you want is not to bother using the CRTL + F5 while assembling the layout of your site/app, so I don’t think you have a simple solution to your problem.

On the other hand, if you want to edit a CSS file through Javascript, you can manipulate the Cssstylesheet.

//Preparação - Criando um CSS Externo para o exemplo.
var blob = new Blob(
    [document.getElementById("templStyle").innerHTML],
    { type: "text/css" }
);
var link = document.createElement("link");
link.href = URL.createObjectURL(blob);
link.title = 'blob';
link.rel = 'stylesheet';

document.head.appendChild(link);

//Inicio do Exemplo.
var getStyleSheetByTitle = function (title) {
    return [].filter.call(document.styleSheets, function(styleSheet, indice) {
        return styleSheet.title == title;
    })[0];
}

var getStyleSheetRule = function (styleSheet, selector) {
    return [].filter.call(styleSheet.rules, function(rule, indice) {
        return rule.selectorText == selector;
    })[0];
}

var btAtualizarCss = document.getElementById("btAtualizarCss");
btAtualizarCss.addEventListener("click", function (event) {
    var cssBlob = getStyleSheetByTitle("blob");
    getStyleSheetRule(cssBlob, "span:hover").style.color = null;
    getStyleSheetRule(cssBlob, "label").style.color = "yellow";
})
<span>Span: Hello World</span>
<br />
<label>Label: Hello World</label>
<br />
<button id="btAtualizarCss">Remover Hover do Span e Mudar Cor do Label</button>

<!-- este template será utilizado para poder criar um CSS Externo para este exemplo -->
<script id="templStyle" type="text/trmplate">
    span { color: green; }
    span:hover { color: yellow; }
    label { color: blue; }
    label:hover { color: red; }
</script>

I named the title of <link /> so that I had an easy way to find the right link, otherwise I would have to look for the CSS by href.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.