ArticleZip > Sharepoint 2013 Add Javascript After Whole Page Load

Sharepoint 2013 Add Javascript After Whole Page Load

To enhance the functionality of your SharePoint 2013 site, you may want to include custom JavaScript code that runs after the entire page has loaded. By doing this, you can ensure that your scripts interact correctly with all elements on the page, providing a seamless user experience. In this helpful guide, we will walk you through the steps to add JavaScript code after the complete loading of a SharePoint 2013 page.

Firstly, to achieve this functionality, you should leverage the `_spBodyOnLoadFunctionNames` array, which holds functions to execute after the entire page has loaded. By adding your custom function to this array, you can guarantee that your JavaScript runs at the appropriate time.

Here's a simple example to demonstrate how to achieve this. Suppose you have a custom JavaScript function named `customFunction` that you want to execute after the whole SharePoint page has loaded. You can add this function to the `_spBodyOnLoadFunctionNames` array using the following code snippet:

Javascript

_spBodyOnLoadFunctionNames.push("customFunction");
function customFunction() {
    // Your custom JavaScript code goes here
    console.log("Custom function executed after page load");
}

By following this approach, your `customFunction` will be automatically invoked after the SharePoint page has completely loaded. This ensures that your code can safely interact with all elements on the page without any conflicts.

Moreover, if you prefer to wait for specific elements to load before executing your JavaScript code, you can utilize jQuery and the `$(document).ready()` function. This function ensures that your script runs only after the entire document, including all elements, has been fully loaded.

Here is an example using jQuery to wait for the document to be ready before executing your custom JavaScript code:

Javascript

$(document).ready(function() {
    // Your custom JavaScript code that requires the entire page to be loaded goes here
    console.log("Custom code executed after the document is ready");
});

By combining SharePoint's `_spBodyOnLoadFunctionNames` array with jQuery's `document ready` function, you can effectively manage the execution of your JavaScript code on your SharePoint 2013 site. This approach helps in avoiding timing issues and ensures that your custom scripts run smoothly without interfering with the page's elements.

In conclusion, by carefully following the steps outlined in this guide, you can seamlessly add custom JavaScript code that executes after the complete loading of a SharePoint 2013 page. Enhance the functionality of your site and provide users with a smoother experience by leveraging these techniques for incorporating JavaScript into your SharePoint environment.