2016-09-28 9 views

答えて

1

例あなたはhighlight_code_worker_functionワーカー機能で、次のコードを、使用するかもしれない複数のコードブロックを強調するために一つだけwebworkerを使用するには1 webworker

を使用。

<script> 

    function highlight_code() { 
     if (typeof (Worker) === undefined) return false; 
     var workerFunction = new Blob(['(' + highlight_code_worker_function.toString() + ')()'], {type: "text/javascript"}); 
     var worker = new Worker(URL.createObjectURL(workerFunction)); 
     var codeBlocks = $('div.readme pre, div.readme code'); 
     worker.onmessage = function(event) { 
      var data = JSON.parse(event.data); 
      codeBlocks.eq(data.index).html(data.result).addClass('hljs'); 
     }; 
     worker.onerror = function() { 
      // do nothing 
     }; 
     codeBlocks.each(function(index) { 
      worker.postMessage(JSON.stringify({index: index, code: $(this).text()})); 
     }); 
     worker.postMessage(JSON.stringify({index: -1})); 
    } 

    function highlight_code_worker_function() { 
     onmessage = function(event) { 
      var data = JSON.parse(event.data); 
      if (data.index === -1) { 
       close(); // close worker 
      } 
      importScripts(''https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.6.0/highlight.min.js''); 
      self.hljs.configure({tabReplace:4}); 
      var result = self.hljs.highlightAuto(data.code); 
      postMessage(JSON.stringify({result: result.value, index: data.index})); 
     } 
    } 

    highlight_code(); 

    </script> 

例使用して、複数のウェブワーカー

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.6.0/styles/monokai_sublime.min.css"> 

    <script type="text/javascript"> 

     function highlight_code() 
     { 
     if (typeof (Worker) === undefined) return false; 
     var workerFunction = new Blob(['(' + highlight_code_worker_function.toString() + ')()'], {type: "text/javascript"}); 
     var localWorkerURL = URL.createObjectURL(workerFunction); 
     $('div.readme pre, div.readme code').each(function() { 
      var code = $(this); 
      var worker = new Worker(localWorkerURL); 
      worker.onmessage = function(event) { code.html(event.data).addClass('hljs'); } 
      worker.postMessage(code.text()); // start worker 
     }); 
     } 

     function highlight_code_worker_function() 
     { 
     onmessage = function(event) { 
      importScripts('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.6.0/highlight.min.js'); 
      self.hljs.configure({tabReplace:4}); 
      var result = self.hljs.highlightAuto(event.data); 
      postMessage(result.value); 
      close(); // close worker 
     } 
     } 

     $(window).on('load', highlight_code); 

    </script> 
関連する問題