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

标签 javascript jquery css

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

我想知道我能否以 promise 的方式做到这一点?目前我正在使用 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
});

最佳答案

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

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);
  });
});

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

关于Javascript Jquery 在外部样式表更改/重新加载 promise 方式后执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35355724/

相关文章:

javascript - react native : synchronously run functions

jquery - 我可以在特定的 div 中显示一个元素 - jQuery

javascript - 进度加载栏在 chrome 和 IE 中不起作用

javascript - JS端了解Tokbox视频分辨率

Javascript:有效地将项目移入和移出固定大小的数组

javascript - 如何动态更改 HTML 表格行中的可点击图像?

JavaScript - 从不同的函数访问不同的变量

python - 如何更改为背景颜色

jquery 在 css3 选项卡上滚动到顶部

javascript - TypeError : rl. 问题不是函数 - NodeJS - 使用 play.js