Programing

ie에서 호환되는 jquery의 스크립트와 같은 외부 CSS 파일로드

lottogame 2020. 11. 14. 09:46
반응형

ie에서 호환되는 jquery의 스크립트와 같은 외부 CSS 파일로드


.getScript 메서드를 사용하여 JS 파일을로드하고 .getScript와 같은 콜백 함수를 사용하는 것과 같이 외부 CSS 파일을로드하는 방법이 있습니까?

$("<link/>", {
   rel: "stylesheet",
   type: "text/css",
   href: "/styles/yourcss.css"
}).appendTo("head");

이것은 FireFox와 유사하지만 IE에서는 작동하지 않습니다.


jQuery 1.4에서 :

$("<link/>", {
   rel: "stylesheet",
   type: "text/css",
   href: "/styles/yourcss.css"
}).appendTo("head");

http://api.jquery.com/jQuery/#jQuery2


응답에 따른 빠른 기능.

loadCSS = function(href) {

  var cssLink = $("<link>");
  $("head").append(cssLink); //IE hack: append before setting href

  cssLink.attr({
    rel:  "stylesheet",
    type: "text/css",
    href: href
  });

};

용법:

loadCSS("/css/file.css");

$("head").append("<link>");
var css = $("head").children(":last");
css.attr({
      rel:  "stylesheet",
      type: "text/css",
      href: "address_of_your_css"
});

OP가 원했던 것은 스타일 시트를 비동기 적으로로드하고 추가하는 것이 었습니다. 이것은 텍스트로 저장된 CSS 규칙 세트에 대해 Chrome 22, FF 16 및 IE 8에서 저에게 효과적입니다.

$.ajax({
    url: href,
    dataType: 'text',
    success: function(data) {
        $('<style type="text/css">\n' + data + '</style>').appendTo("head");                    
    }                  
});

제 경우에는로드 된 CSS가 이전에 이런 방식으로로드 된 CSS를 대체하기를 원합니다. 이를 위해 처음에 "/ * Flag this ID = 102 * /"라고 말한 다음 이렇게 할 수 있습니다.

// Remove old style
$("head").children().each(function(index, ele) {
    if (ele.innerHTML && ele.innerHTML.substring(0, 30).match(/\/\* Flag this ID=102 \*\//)) {
        $(ele).remove();
        return false;    // Stop iterating since we removed something
    }
});

    //load css first, then print <link> to header, and execute callback
    //just set var href above this..
    $.ajax({
          url: href,
          dataType: 'css',
          success: function(){                  
                $('<link rel="stylesheet" type="text/css" href="'+href+'" />').appendTo("head");
                //your callback
            }
    });

Jquery 1.2.6 이상 (위의 멋진 속성 함수 생략).

I am doing it this way because I think that this will ensure that your requested stylesheet is loaded by ajax before you try to stick it into the head. Therefore, the callback is executed after the stylesheet is ready.


Based on your comment under @Raul's answer, I can think of two ways to include a callback:

  1. Have getScript call the file that loads the css.
  2. Load the contents of the css file with AJAX, and append to <style>. Your callback would be the callback from $.get or whatever you use to load the css file contents.

Here is a function that will load CSS files with a success or failure callback. The failure callback will be called just once, if one or more resources fail to load. I think this approach is better than some of the other solutions because inserting a element into the DOM with an HREF causes an additional browser request (albeit, the request will likely come from cache, depending on response headers).

function loadCssFiles(urls, successCallback, failureCallback) {

    $.when.apply($,
        $.map(urls, function(url) {
            return $.get(url, function(css) {
                $("<style>" + css + "</style>").appendTo("head");
            });
        })
    ).then(function() {
        if (typeof successCallback === 'function') successCallback();
    }).fail(function() {
        if (typeof failureCallback === 'function') failureCallback();
    });

}

Usage as so:

loadCssFiles(["https://test.com/style1.css", "https://test.com/style2.css",],
    function() {
    alert("All resources loaded");
}, function() {
    alert("One or more resources failed to load");
});

Here is another function that will load both CSS and javascript files:

function loadJavascriptAndCssFiles(urls, successCallback, failureCallback) {

    $.when.apply($,
        $.map(urls, function(url) {
            if(url.endsWith(".css")) {
                return $.get(url, function(css) {
                    $("<style>" + css + "</style>").appendTo("head");
                });
            } else {
                return $.getScript(url);
            }
        })
    ).then(function() {
        if (typeof successCallback === 'function') successCallback();
    }).fail(function() {
        if (typeof failureCallback === 'function') failureCallback();
    });

}

$("#pageCSS").attr('href', './css/new_css.css');

참고URL : https://stackoverflow.com/questions/2685614/load-external-css-file-like-scripts-in-jquery-which-is-compatible-in-ie-also

반응형