3

Always looking to make CSR development easier...

This the typical CSR programming pattern:

We hardcode the filename inside the CSR file

SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function () {
    function init() {
        var overrides = {Templates: {Fields: {}}};
        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrides);
    }
    var csrfile = "~siteCollection/Style Library/MYHARDCODEDCSRFILENAME.js";
    csrfile=SPClientTemplates.Utility.ReplaceUrlTokens(csrfile);
    RegisterModuleInit(csrfile, init);
    init();
});

Now I wonder

The script executes onload, so it is the last script added to the DOM

Can we get the filename from the last <script> definition ??

var scripts = document.querySelectorAll("[type='text/javascript']");
var csrfile = scripts[scripts.length-1].src.split('?')[0];
SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function () {
    function init() {
        console.info('CSR init');
        var overrides = {Templates: {Fields: {}}};
        overrides.Templates.OnPostRender = function() {
          console.info('OnPostRender');
        };
        SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrides);
    }
    RegisterModuleInit(csrfile, init);
    init();
});

a quick test seems to work...

Questions:

  • Office365/SharePoint Online accepts absolute URLs, so no need to use tokens,
    Does an absolute URL have an impact on how SharePoint internals deal with the script?

  • I now chop off the ?ctag=9$$16.0.5104.1212 parameter, any issues there?

  • Can WebWorkers or other mulitthreading hamsters interfere?

Lessons learned:

  • This works for me because I have one CSR file that rule them all

  • We are all sheep, blindly copy/pasting code...

    SPClientTemplates.Utility.ReplaceUrlTokens(csrfile);
    

    Has 932.000 Google results,
    But is nothing but a wrapper function, these 7 Google results (now 8 )are not sheep,
    it is one less function call so shorter, better to read and faster:

    SPClientRenderer.ReplaceUrlTokens(csrfile);
    

jmx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.