2015-02-08 204 views
0

我觉得我没有在这里获得概念承诺。我试图获得外部的CSS文件中使用并将其附加到HTML。然后我想用这些内容做点什么。我在这里做错了什么?这是我在翻阅和阅读文档之后所处的时间比我想承认的要长。jQuery.when不等待完成

<script type="text/javascript"> 

     $(function() { 
      $.when(convertPageCssToInlineStyle()).then(
       alert(document.documentElement.outerHTML) 
      ); 


     }); 

     var convertPageCssToInlineStyle = function() { 
      var links = $("html").find("link[rel=stylesheet]"); 

      links.attr("href", function(i, value) { 
       if (!window.location.origin) 
        window.location.origin = window.location.protocol + "//" + window.location.host + value; 

       $.when(
        $.get(window.location.origin, function(response) { 
         $('<style />').text(response).appendTo($('head')); 
        }) 
       ); 

      }); 
     }; 
    </script> 

回答

1

您的convertPageCssToInlineStyle函数必须返回一个承诺。现在它不会返回任何东西。

事情是这样的....

$(function() { 
     $.when(convertPageCssToInlineStyle()).then(
      alert(document.documentElement.outerHTML) 
     ); 


    }); 

    var convertPageCssToInlineStyle = function() { 
     var links = $("html").find("link[rel=stylesheet]"); 
     var deferred = $.Deferred(); 
     links.attr("href", function(i, value) { 
      if (!window.location.origin) 
       window.location.origin = window.location.protocol + "//" + window.location.host + value; 

      $.when(
       $.get(window.location.origin, function(response) { 
        $('<style />').text(response).appendTo($('head')); 
        deferred.resolve(); 
       }) 
      ); 
     }); 
     return deferred.promise(); 
    }; 
</script> 
+0

绝对有意义,你能解释一下如何做到这一点吗? – Chazt3n 2015-02-08 00:56:36

+0

@ Chazt3n - 好的,我提供了一个编码示例。 (没有对它进行测试,它可能有缺陷,但它给你一个方法的想法)。 – 2015-02-08 01:01:22

+0

所以我仍然得到相同的行为。难道这与我使用attr函数循环遍历结果集有关吗? – Chazt3n 2015-02-08 01:16:19

2

我能够通过映射我的诺言到一个数组,然后从This question's answer

处理一次全部使用代码来解决这个问题
<script type="text/javascript"> 
    $(function() { 

     var links = $("html").find("link[rel=stylesheet]"); 
     var newLinks = []; 

     if (!window.location.origin) 
      window.location.origin = window.location.protocol + "//" + window.location.host; 

     links.attr("href", function(i, value) { 
      newLinks.push(window.location.origin + value); 
     }); 

     var promises = $.map(newLinks, function(value) { 
      return $.get(value, function(response) { 
       $('<style />').text(response).appendTo($('head')); 
      }); 
     }); 

     $.when.apply($, promises).then(function() { 
      console.log(document.documentElement.outerHTML); 
     }); 
    }); 

</script>