Forum Discussion

Mahendran Dhandapani's avatar
Mahendran Dhandapani
Copper Contributor
Sep 08, 2018

Loading JS files in <head> tag using SPFx. Similar to ScriptLink !

This is the exact scenario we are in. @PopWarner have asked right questions but no acceptable responses :(
Any update on this?

 

We want to load our JS before the body tag renders. Any solution on that? Tried ApplicationCustomizer but it is not we want because it is just inserting the reference on head tag after body tag renders.

 

Do you have any solution on new SPFx v1.6?

 

Use Case: Some analytics scripts wants to be called / rendered before the <body> tag.

 

Same question is posted on GitHub

  • Steve Johnson's avatar
    Steve Johnson
    Copper Contributor

    What about this in the Application.Customizer? Would this not load the script into the header?

     

    export default class CustomJsApplicationCustomizer
    extends BaseApplicationCustomizer<IJsApplicationCustomizerProperties> {
    private _externalJsUrl: string = "https://<tenant>.sharepoint.com/sites/<site>/CDN/someJSfile.js";
     
    @override
    public onInit(): Promise<void> {

     

    /* LOADING THE JS */
    let scriptTag: HTMLScriptElement = document.createElement("script");
    scriptTag.src=this._externalJsUrl;
    scriptTag.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(scriptTag);
    console.log ("Loading some JS file");
     
    return Promise.resolve();
    }
    }

     

    • Mahendran Dhandapani's avatar
      Mahendran Dhandapani
      Copper Contributor

      On the documentation, it is mentioned that;

       

      The logic for your Application Customizer is contained in the onInit method, which is called when the client-side extension is first activated on the page. This event occurs after this.context and this.properties are assigned. As with web parts, onInit()returns a promise that you can use to perform asynchronous operations.

       

      Client-side extensions are activated when body tag renders. Correct me if I'm wrong. This is not we wanted. 

       

      On the classic SharePoint, if we install a custom script (ScriptLink with sequence order) then it loads as part of head tag. It does not get injected (or load) after the body tag renders.