developer tip

페이지를 다시로드하지 않고 CSS를 다시로드 할 수있는 쉬운 방법이 있습니까?

optionbox 2020. 9. 24. 07:45
반응형

페이지를 다시로드하지 않고 CSS를 다시로드 할 수있는 쉬운 방법이 있습니까?


스타일 시트를 다시로드하고 페이지를 다시로드 할 필요없이 적용하는 미리보기 기능이있는 라이브 인 페이지 CSS 편집기를 만들려고합니다. 이것에 대해 가장 좋은 방법은 무엇입니까?


"편집"페이지에서 일반적인 방식 ( <link>태그 포함) 으로 CSS를 포함하는 대신 태그에 모두 작성합니다 <style>. 해당 innerHTML속성을 편집하면 서버로의 왕복 없이도 페이지가 자동으로 업데이트됩니다.

<style type="text/css" id="styles">
    p {
        color: #f0f;
    }
</style>

<textarea id="editor"></textarea>
<button id="preview">Preview</button>

jQuery를 사용하는 자바 스크립트 :

jQuery(function($) {
    var $ed = $('#editor')
      , $style = $('#styles')
      , $button = $('#preview')
    ;
    $ed.val($style.html());
    $button.click(function() {
        $style.html($ed.val());
        return false;
    });
});

그리고 그게 다야!

정말 멋지게 만들고 싶다면 원치 않는 부작용이 발생할 수 있지만 텍스트 영역의 keydown에 함수를 연결하십시오 (입력 할 때 페이지가 계속 변경됨).

편집 : 테스트되고 작동합니다 (적어도 Firefox 3.5에서는 다른 브라우저에서는 괜찮습니다). 여기에서 데모보기 : http://jsbin.com/owapi


귀하의 상황에 적용되지 않을 수 있지만 외부 스타일 시트를 다시로드하는 데 사용하는 jQuery 함수는 다음과 같습니다.

/**
 * Forces a reload of all stylesheets by appending a unique query string
 * to each stylesheet URL.
 */
function reloadStylesheets() {
    var queryString = '?reload=' + new Date().getTime();
    $('link[rel="stylesheet"]').each(function () {
        this.href = this.href.replace(/\?.*|$/, queryString);
    });
}

이를 위해 jQuery를 사용할 필요가 전혀 없습니다. 다음 JavaScript 함수는 모든 CSS 파일을 다시로드합니다.

function reloadCss()
{
    var links = document.getElementsByTagName("link");
    for (var cl in links)
    {
        var link = links[cl];
        if (link.rel === "stylesheet")
            link.href += "";
    }
}

앤드류 데비의 세련되지 유행 프로젝트를 체크 아웃 - http://aboutcode.net/vogue/


하나 더 jQuery 솔루션

ID가 "css"인 단일 스타일 시트의 경우 다음을 시도하십시오.

$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');

전역 scrope가있는 함수로 래핑하고 Chrome의 개발자 콘솔 또는 Firefox의 Firebug에서 사용할 수 있습니다.

var reloadCSS = function() {
  $('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};

Vanilla JS와 한 줄의 짧은 버전 :

for (var link of document.querySelectorAll("link[rel=stylesheet]")) link.href = link.href.replace(/\?.*|$/, "?ts=" + new Date().getTime())

또는 확장 :

for (var link of document.querySelectorAll("link[rel=stylesheet]")) {
  link.href = link.href.replace(/\?.*|$/, "?ts=" + new Date().getTime())
}

이전 솔루션을 기반으로 JavaScript 코드로 책갈피를 만들었습니다.

javascript: { var toAppend = "trvhpqi=" + (new Date()).getTime(); var links = document.getElementsByTagName("link"); for (var i = 0; i < links.length;i++) { var link = links[i]; if (link.rel === "stylesheet") { if (link.href.indexOf("?") === -1) { link.href += "?" + toAppend; } else { if (link.href.indexOf("trvhpqi") === -1) { link.href += "&" + toAppend; } else { link.href = link.href.replace(/trvhpqi=\d{13}/, toAppend)} }; } } }; void(0);

Firefox의 이미지 :

enter image description here

What does it do?

It reloads CSS by adding query string params (as solutions above):


Yes, reload the css tag. And remember to make the new url unique (usually by appending a random query parameter). I have code to do this but not with me right now. Will edit later...

edit: too late... harto and nickf beat me to it ;-)


i now have this:

    function swapStyleSheet() {
        var old = $('#pagestyle').attr('href');
        var newCss = $('#changeCss').attr('href');
        var sheet = newCss +Math.random(0,10);
        $('#pagestyle').attr('href',sheet);
        $('#profile').attr('href',old);
        }
    $("#changeCss").on("click", function(event) { 
        swapStyleSheet();
    } );

make any element in your page with id changeCss with a href attribute with the new css url in it. and a link element with the starting css:

<link id="pagestyle" rel="stylesheet" type="text/css" href="css1.css?t=" />

<img src="click.jpg" id="changeCss" href="css2.css?t=">

Another answer: There's a bookmarklet called ReCSS. I haven't used it extensively, but seems to work.

There's a bookmarklet on that page to drag and drop onto your address bar (Can't seem to make one here). In case that's broke, here's the code:

javascript:void(function()%7Bvar%20i,a,s;a=document.getElementsByTagName('link');for(i=0;i%3Ca.length;i++)%7Bs=a[i];if(s.rel.toLowerCase().indexOf('stylesheet')%3E=0&&s.href)%20%7Bvar%20h=s.href.replace(/(&%7C%5C?)forceReload=%5Cd%20/,'');s.href=h%20(h.indexOf('?')%3E=0?'&':'?')%20'forceReload='%20(new%20Date().valueOf())%7D%7D%7D)();

In a simple manner you can use rel="reload" instead of rel="stylesheet" .

<link rel="preload" href="path/to/mystylesheet.css" as="style" onload="this.rel='stylesheet'">

simple if u are using php Just append the current time at the end of the css like

<link href="css/name.css?<?php echo 
time(); ?>" rel="stylesheet">

So now everytime u reload whatever it is , the time changes and browser thinks its a different file since the last bit keeps changing.... U can do this for any file u force the browser to always refresh using whatever scripting language u want

참고URL : https://stackoverflow.com/questions/2024486/is-there-an-easy-way-to-reload-css-without-reloading-the-page

반응형