Javascript Jquery在外部样式表更改/重新加载承诺方式后执行代码

Javascript Jquery在外部样式表更改/重新加载承诺方式后执行代码,javascript,jquery,css,Javascript,Jquery,Css,我有一个包含两个主题的页面,允许用户通过组合框进行更改。在combobox的change事件中,我使用jquery删除当前样式表并附加新的样式表。现在我想在新样式表完成加载后运行一些代码(重新计算元素的大小,…) 我想知道我是否能用承诺的方式做这件事?目前我使用的是setTimeout,但在我看来时间不够好。我在想这样的事情: var oldStylesheet = ...; var newStylesheet = ...; $.when(function() { var d = $.

我有一个包含两个主题的页面,允许用户通过组合框进行更改。在combobox的
change
事件中,我使用jquery删除当前样式表并附加新的样式表。现在我想在新样式表完成加载后运行一些代码(重新计算元素的大小,…)

我想知道我是否能用承诺的方式做这件事?目前我使用的是
setTimeout
,但在我看来时间不够好。我在想这样的事情:

var oldStylesheet = ...;
var newStylesheet = ...;

$.when(function() {
    var d = $.Deferred;

    oldStylesheet.remove();
    newStylesheet.append();

    // when new stylesheet completed loading: d.resolve();

    return d.promise;
}).done(function() {
    // code to run after new stylesheet has completed loading
});

假设组合框中选项的值是样式表的url,您可以在jQuery中为您的用例使用
$.get()
AJAX函数:

var oldStylesheet = ...;
$('.theme-select').on('change', function(){
  var stylesheet = $(this).val();
  $.get(stylesheet , function(response){
   oldStylesheet.remove();
   // Check if the style tag in which the file will be appended is in place
   // if not create one
   if (!$('.custom-theme').length){
       $('head').append('<style class="custom-theme"></style>');
   }
   // Add/Replace the new style with the old one.
   $('.custom-theme').text(response);
  });
});
var oldStylesheet=。。。;
$('.theme select')。在('change',function()上{
var样式表=$(this.val();
$.get(样式表、函数(响应){
oldStylesheet.remove();
//检查将附加文件的样式标记是否到位
//如果没有,创建一个
如果(!$('.custom theme')。长度){
$('head')。追加('');
}
//用旧样式添加/替换新样式。
$('.custom theme')。文本(响应);
});
});

我还没有测试过它,所以我不知道是否有错误。

这可能有助于从服务器加载新样式表所需的时间,但仍然有浏览器重新渲染样式所需的时间。在古老的浏览器/PC上,当您试图计算尚未重新渲染的元素大小时,这将是一个问题。这是所有的理论,但我会做测试和更新后。谢谢