Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: <link rel="preload"> in index.html for generated web worker

I have a Angular app containing a web worker implementation (generated via ng generate webWorker).

I want to mark the given web-worker for preloading, like this:

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
   ...
    <link rel="prefetch" href="worker.js" />
   ...
  </head>
 ....
</html>

The problem is that the name of the worker.js file is generated via Angular CLI, e.g. 0.7841408a8c7c04e45900.worker.js (bundled from worker.ts)

Is there a way to put a placeholder of the filename into the index.html, which is replaced by the actual filename at build time?

like image 657
kerosene Avatar asked Nov 28 '19 09:11

kerosene


People also ask

What is rel preload in HTML?

The preload value of the <link> element's rel attribute lets you declare fetch requests in the HTML's <head> , specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in.

How do you preload a script?

The rel="preload" attribute value is used to preload assets. It can be applied to several file formats, including CSS, JS, fonts, images, and more. Depending on the type of file you would like to preload, the corresponding as attribute may also need to be included along with rel="preload" .

How do I preload CSS files?

Currently, you load CSS and JS through the link tag. So, to preload those resources, all you need is to change the rel attribute to preload and add the as=”style” attribute (or as=”script” for JavaScript).


1 Answers

In angular.json file, mention the worker file path in the scripts section.

build: {
    ...,
    options: {
        "scripts": ['./worker.js']
    }
}

By default, Angular will inject the files mentioned in the scripts array directly into the html. If you do not want the angular to inject you can pass the configuration object as below:

"scripts": [
  { 
    "input": "./worker.js", 
    "inject": false, 
    "bundleName": "worker" 
  }
]

In the above case, you can have more control over the name of the bundled js file. Since you know the name of the bundle, you can directly specify it in your html as

<link rel="prefetch" href="worker.js">

Hope this helps.

like image 123
Indragith Avatar answered Sep 27 '22 21:09

Indragith