Search code examples
c#asp.net.netasp.net-mvcprefetch

ASP.Net MVC Generate DNS Prefetch Tags


Is there a way to find all the src="" urls when rendering a ASP.net MVC page in the view to then generate DNS prefetch tags on the fly?

https://www.chromium.org/developers/design-documents/dns-prefetching


Solution

  • If I understood correctly I can tell you the following:

    Option #1: (Not a pretty solution but would work.)

    NOTE: for this try to use simple Javascript and not rely on JQuery or other (since then you still need to "load" the .JS file for that and that is ruining the point of your question.

    Process your src/href or some other predefined property tag with some kind of "OwnLogic" to define the "base target", but in a way that the browser would not be able to initiate the request to obtain that image or other file. Example:

    <img url="" class="DNS_BaseTarget" DNS_BaseTarget="smiley.gif||myCDNPointerInfo" alt="">
    

    Then, with javascript, get a list of all elements that uses the class DNS_BaseTarget and then read the property value and update the "src" tag. At the same time you can inject by javascript inject all the '<link rel="dns-prefetch" href="https://cdn.yourTargetDomain.com">' that you will use based on the information you just processed.

    I did not tested this concept, so "lag" or some sort of delay in the client might be expected (but maybe not noticeble by the user).

    Option #2:

    The View Result Execution Process (in MVC life cycle) tell us that the method 'Render()' is the last one to be executed. With this being said, you can create your own custom override logic Example: intercept view rendering to add HTML/JS on all partial views? How to intercept view rendering to add HTML/JS on all partial views?

    With this concept of trying to "process" the final html before sending it to the user, you could somehow "parse" the file.... try to get all the 'src/href' and then inject all the '<link rel="dns-prefetch" href="https://cdn.yourTargetDomain.com">' that you will use.