Search code examples
javascripthtmlweb-worker

Cannot read property of NULL


I have the following html file in which I try to highlight some code using a web worker:

<link rel="stylesheet" href="./highlight/styles/default.css">
<script src="./highlight/highlight.pack.js"></script>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>

	if (typeof(Worker) !== "undefined") {

    	addEventListener('load', function() {
			var code = document.querySelector('#code');
			var worker = new Worker('worker.js');
			worker.onmessage = function(event) { code.innerHTML = event.data; }
			worker.postMessage(code.textContent);
		})
	
	} else {
	}


</script>


<pre><code>
// This is a generated file with many packages
`ifdef MACRO_1
`else
package pkg_1;
  typedef logic [1:0] t;
  typedef enum t {
      IDLE = 2'd0
    , ARMED = 2'd1
    , WRITE = 2'd2
    , BUSY = 2'd3
  } e;
</code></pre>

But I get an error saying: Uncaught TypeError: Cannot read property 'textContent' of null (worker.postMessage(content.textContent));

Is there a solution?


Solution

  • Add id="code" attribute on code element: https://jsbin.com/daqijafoca/edit?html,output

    <link rel="stylesheet" href="./highlight/styles/default.css">
    <script src="./highlight/highlight.pack.js"></script>
    
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    
        if (typeof(Worker) !== "undefined") {
    
            addEventListener('load', function() {
                var code = document.querySelector('#code');
                var worker = new Worker('worker.js');
                worker.onmessage = function(event) { code.innerHTML = event.data; }
                worker.postMessage(code.textContent);
            })
    
        } else {
        }
    
    
    </script>
    
    
    <pre><code id="code">
    // This is a generated file with many packages
    `ifdef MACRO_1
    `else
    package pkg_1;
      typedef logic [1:0] t;
      typedef enum t {
          IDLE = 2'd0
        , ARMED = 2'd1
        , WRITE = 2'd2
        , BUSY = 2'd3
      } e;
    </code></pre>