locked
Defer loading of Javascript approach in asp.net mvc RRS feed

  • Question

  • User-268378125 posted

    I'm going to implement Defer loading of JavaScript approach because as per current structure JavaScript is being called in <head> element which is taking long response time. So I just want to add this JavaScript after complete DOM load. Here is code in cshtml file

    Layout.cshtml

    <head>
    @Scripts.Render("~/bundles/javascript")
    </head>

    Rendered html view source:

    <head>
        <script src="/bundles/javascript?v=abcdefghikeriotterpoggkjs-fskdf"></script>
    </head>

    Here is what I'm planning to do: I will remove the @Scripts.Render("~/bundles/javascript") from <head> section. Then copy the src value from rendered view source and use given below

    <script type="text/javascript">
        // Add a script element as a child of the body
        function downloadJSAtOnload() {
            var element = document.createElement("script");
            element.src = "/bundles/javascript?v=abcdefghikeriotterpoggkjs-fskdf";
            document.body.appendChild(element);
        }
        // Check for browser support of event handling capability
        if (window.addEventListener)
            window.addEventListener("load", downloadJSAtOnload, false);
        else if (window.attachEvent)
            window.attachEvent("onload", downloadJSAtOnload);
        else
            window.onload = downloadJSAtOnload;
    </script>

    Am I doing correct? My doubt is Does this value 

    v=abcdefghikeriotterpoggkjs-fskdf

    throughout the application remain same or it can be changed. If it remain same then I think there won't be any issue. Please suggest.

    Sunday, November 27, 2016 6:22 AM

All replies

  • User1724605321 posted

    Hi ,

    Seems you are following this article :
    https://varvy.com/pagespeed/defer-loading-javascript.html 

    Just try append the specified js files with multi script elements and check whether it works .

    Best Regards,

    Nan Yu

    Monday, November 28, 2016 6:28 AM
  • User-268378125 posted

    Yes correct...so here I have 2 questions:
    1) Does above implementation which I did in post is correct
    2) Does this value

    v=abcdefghikeriotterpoggkjs-fskdf

    remain same through the applications?

    because in cshtml file it's rendered through

    @Scripts.Render("~/bundles/javascript")

    but I copy that value from view source and appended in script code.

    Monday, November 28, 2016 12:37 PM
  • User-693045842 posted

    Hi ,

    Does above implementation which I did in post is correct

    Then try it to check whether it works .

    remain same through the applications?

    As @Nan Yu  said , "append the specified js files with multi script elements" , not mixed use bundles

    :)

    Friday, December 2, 2016 8:24 AM