Back Avoid jQuery(document).ready in ASCX control



Due specific SharePoint client side initialization life cycle, it is recommended to avoid using $(document).ready and windows.load = function() { …};.

It is a common practice to modify content from JavaScript. The end user can’t identify the moment when page has been changed, it looks like all page content rendered on server side. For example, SharePoint list views are used same approach named CSR.

$(document).ready used due to two reasons:

  • run code AFTER DOM constructed
  • run code BEFORE page rendered

Many times $(document).ready fires later than expected. Actually it handles DOMContentLoaded event. In case of static HTML content, DOMContentLoaded is raised right after content loaded from server(!) and before rendered. But SharePoint pages use JavaScript to build markup, offen when content is not loaded yet, thus it is unclear when the DOMContentLoaded event fires.


  • It is recommended to keep the following rules:
  • Use SP.SOD.executeOrDelayUntilScriptLoaded to manage scripts load order NOT depending on sharepoint .js file.
  • Use SP.SOD.execute and SP.SOD.executeFunc to manage scripts load order depending on sharepoint .js file.
  • Use arrays _spBodyOnLoadFunctionNames (sp2010) or _spBodyOnLoadFunctions (sp2013) to solve simple tasks on the SharePoint pages like list forms, views or web part pages. Be aware that content is often added after the page is loaded, for example: Web Parts in MDS, option tags in lookup fields, cascading lookups. Be sure you work with ready-to-proceed elements.
  • In case of Minimal Download Strategy (MDS) use RegisterModuleInit function call to get your script loaded while asyc load occur
window.myappName$ = window.myappName$ || jQuery.noConflict(true);

(function ($) {
    if (!_spBodyOnLoadCalled) {
    } else {

    function pageLoad() {
        $('#pageTitle span').text('Hello from jQuery');

    RegisterModuleInit(_spPageContextInfo.webServerRelativeUrl + '/appname/script.js', pageLoad);


Consider mQuery

m$.ready(function () {
    // DO STUFF

In general mQuery does not play significant role and can’t be consider as common solution. It uses onDemandload mode on many pages. That means it have to be used as

SP.SOD.execute("mquery.js", "m$.ready", function () {

    // DO STUFF



Last updated: 1/9/2016
Login to leave a comment.