Ok,
So I can't say this is best practice but it seems pretty legit:
If you haven't played with Web Workers, I highly suggest at least taking a peek at the API.
<head>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous">
</script>
<title>Time for Web Workers!</title>
</head>
<body id="body">
<script type="text/javascript">
var worker = new Worker("js.js");
worker.addEventListener("message",
function (evt) {
var script = document.createElement("script");
script.innerHTML = evt.data;
document.getElementById('body').appendChild(script);
},false);
worker.postMessage(1);
</script>
Web Workers breaks the limit of single threading when using javascript. The big setback with workers are that they cannot access the dom. The most that they can do is compute and pass data via messages.
Ah, but messages!
This is where it gets a bit messy, but stick with me.
var worker = new Worker("js.js");
// any data can be used as arg, but needed to trigger 'messages' listener
worker.postMessage(1);
I first tried to send the postMessage()
function to create a new Worker
using a local js file. This works, but it causes the jQuery to remain undefined
as the script is not availble to the thread. Separate threads, separate resources >_<
To get around this, we need the Worker
to send the code back to the main thread to be executed under the dom's jQuery script. We can do this by setting our local js file to listen for the message event and return it's code base, as a string.
This can be done by using a dummy to import your minified local file and parse as a string, or by simply creating a string from your minified script and using it like so:
addEventListener("message",
function (evt) {
var script =
"$(document).ready(
function() {
var thisThing = 'blah';alert(thisThing);
})";
postMessage(script);
}, false);
Back at the main thread, we set an event listener to listen for messages as well. In this function, we need to create a new <script>
element and insert the stringified codebase into it before finally appending it to the body
.
worker.addEventListener("message",
function (evt) {
var script = document.createElement("script");
script.innerHTML = evt.data;
document.getElementById('body').appendChild(script);
},false);
Note
- I have not tested this with a large script
- I have only used a local development server to test this
- I have not tested any
$(document).ready()
-heavy code in the local script, so I do not know if this will even fix your issue..
- I had fun doing this :P
tag? That should eliminate the warning and improve performance.
– Paul Nov 29 '16 at 00:30