簡體   English   中英

將Ajax工具包腳本移動到頁面底部

[英]Moving Ajax toolkit scripts to the bottom of the page

我正在努力改進我們的一個網站PageSpeed見解得分,在我們徘徊在90左右的那一刻,如果可能的話,我們想要進入90年代中期。

我們遇到的一個棘手問題是,Ajax工具包腳本管理器正在頁面頂部生成其腳本,谷歌將此標記為“ 應該修復 ”問題,並抱怨腳本呈現阻止,應該移動到頁面底部或異步加載或通過defer屬性加載。

我正在使用以下內容將我們的腳本合並到一個.js文件中以最小化請求:

<ajaxToolkit:ToolkitScriptManager ID="manScript" LoadScriptsBeforeUI="false" runat="server" EnableViewState="false" ScriptMode="Release">

    <CompositeScript ScriptMode="Release" Path="/CMSGlobalFiles/Js/combinedajax.min.js">
        <Scripts>
            <asp:ScriptReference Name="WebForms.js" Path="/CMSGlobalFiles/Js/aspnet/WebForms.js" Assembly="System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
            <asp:ScriptReference Name="MicrosoftAjax.js" Path="/CMSGlobalFiles/Js/aspnet/MicrosoftAjax.js"  />
            <asp:ScriptReference Name="MicrosoftAjaxWebForms.js" Path="/CMSGlobalFiles/Js/aspnet/MicrosoftAjaxWebForms.js" />
        </Scripts>
    </CompositeScript>

</ajaxToolkit:ToolkitScriptManager>

有沒有辦法在輸出的CompositeScript標簽上設置deferasync 或者將其移動到頁面底部的任何其他方式?

我嘗試過以下方法:

protected override void Render(HtmlTextWriter writer)
{
    StringWriter output = new StringWriter();
    base.Render(new HtmlTextWriter(output));

    string outputAsString = output.ToString();

    if(outputAsString.Contains("<script src=\"/CMSGlobalFiles/Js/combinedajax.min.js\" type=\"text/javascript\"></script>"))
    {
        outputAsString = outputAsString.Replace("<script src=\"/CMSGlobalFiles/Js/combinedajax.min.js\" type=\"text/javascript\"></script>", string.Empty);
    }

    writer.Write(outputAsString);
}

然后手動在頁面底部包含對腳本的引用:

<script type="text/javascript">
    function downloadJSAtOnload() {
        createScript("/CMSGlobalFiles/Js/combinedajax.min.js?v=1");
        createScript("//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js");
        createScript("/cmsglobalfiles/js/vendor/modernizr.js");
        createScript("/cmsglobalfiles/js/main.min.js");
        createScript("/cmsglobalfiles/js/vendor/wow.min.js");
    }

    function createScript(path) {
        var element = document.createElement("script");
        element.src = path;
        document.body.appendChild(element);
    }

    if (window.addEventListener)
        window.addEventListener("load", downloadJSAtOnload, false);
    else if (window.attachEvent)
        window.attachEvent("onload", downloadJSAtOnload);
    else window.onload = downloadJSAtOnload;
</script>

這將刪除生成的復合腳本並在結束正文標記之前創建一個新的復合腳本,這會使我們的分數達到95但我認為加載太晚,因為我們遇到了很多控制台錯誤:

ReferenceError:未定義Sys

WebForm_InitCallback未定義

這表明腳本管理器壞了,有沒有辦法實現這一點?

我使用ajax控件工具包版本15.1.4.0 ,你使用ScriptManager而不是ToolkitScriptManager但你可以設置LoadScriptsBeforeUI="False"並在</form>之前渲染。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM