Azure B2C: Run script after page loads

metalheart 411 Reputation points
2024-02-06T13:01:09.56+00:00

I'm using custom policies and have run into a regression after moving scripts from BODY to the HEAD element when migrating to the newest page templates.

I'm facing an issue that when the script runs the page elements are not yet in place.

The issue can be reproduced on a sign up idpselector page selecting the SignUpWithLogonEmailExchange button element which is not found when the script runs, but is in the DOM later - I understand there is a timing issue and some B2C scripts must run first that create this element and only then I can run my script.

How do I register my scripts so that they run after everything B2C-related is in place?

This is how my script is registered in my custom content definition (page template urn:com:microsoft:aad:b2c:elements:contract:providerselection:1.2.4):



This is the script:

console.log('idpSelector.js running');

// add divider between local and social
$(document).ready(function() {
    console.log('idpSelector.js running on content load');
    
    var localSignUpBtn = document.getElementById('SignUpWithLogonEmailExchange');
    if (!localSignUpBtn)
    {
        console.log('idpSelector.js: no SignUpWithLogonEmailExchange');
        return;
    }
});

and the console output:

idpSelector.js running
idpSelector.js running on content load
idpSelector.js: no SignUpWithLogonEmailExchange
Microsoft Security | Microsoft Entra | Microsoft Entra External ID
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Marilee Turscak-MSFT 37,206 Reputation points Microsoft Employee Moderator
    2024-02-07T22:38:13.1133333+00:00

    Hi @metalheart ,

    You can add the "defer" element to the page to specify that the script is executed after the page has finished parsing:

     <script src="my-script.js" defer></script>
    

    This is specified here: https://learn.microsoft.com/en-us/azure/active-directory-b2c/javascript-and-page-layout?pivots=b2c-custom-policy

    Or you could use <body onload="script();">

    There are some other solutions noted here, which you could leverage as well.

    Let me know if this helps and if you run into any issues.

    If the information helped you, please Accept the answer. This will help us and improve searchability for others in the community who may be researching similar questions.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.