Loading And Executing Javascript In Sharepoint 2013

What is JavaScript and Why Use It in SharePoint

JavaScript is a programming language that enables dynamic interactivity and client-side scripting on websites and applications. With JavaScript, developers can create custom functions that execute in the user’s web browser instead of on the web server. This allows for responsive experiences without needing to reload pages.

Using JavaScript in SharePoint pages and sites unlocks additional possibilities like:

  • Validating form data before submission
  • Dynamically showing and hiding page elements
  • Animating transitions and slideshows
  • Sending data to and from the SharePoint API
  • And much more

By enhancing sites with JavaScript, SharePoint designers can boost engagement, streamline workflows, and create more intuitive interfaces.

Methods to Load JavaScript in SharePoint

Using Script Editor Web Parts

The most straightforward approach to add JavaScript to a SharePoint page is by using a Script Editor web part. The Script Editor web part enables pasting JavaScript directly into the web part properties. The code will then execute on that page.

To use a Script Editor web part:

  1. Edit the SharePoint page
  2. Add a Script Editor web part
  3. Paste JavaScript code into the text editor field in the web part properties
  4. Save the page

This method is great for page-specific scripts. However, the code is not reusable across sites.

Adding Links to JavaScript Files in Master Pages

For reusable JavaScript that should load across an entire SharePoint site, add in the section

  • Upload the .js file to SiteAssets or Style Library
  • Save and publish the master page
  • Embedding Scripts in Web Part Properties

    Some web parts enable adding JavaScript through web part properties. For example, the Content Editor and Media web parts have fields for embedded script.

    Using these fields can be easier for quick scripts related to that web part. But they should be used sparingly, as embedded scripts can clutter and complicate longer pages.

    Injecting Scripts with Custom Code

    For complex JavaScript needs, custom code can load scripts through various events and callbacks. Examples include the Client Side Rendering (CSR) API, remote event receivers, or injecting via link elements.

    Loading scripts dynamically through code enables advanced scenarios. But requires JavaScript and SharePoint development expertise.

    Executing JavaScript in SharePoint

    Understanding Client-Side vs Server-Side Execution

    Client-side execution means the script runs in the user's web browser, without needing to post back to the server. This leads to faster, more responsive user experiences. Code can respond to interactions like button clicks locally.

    Server-side execution means the scripts runs on the web servers, then returns data to populate the rendered pages. Server-side code has access to system resources, but calls require full page reloads.

    In SharePoint specifically, most custom JavaScript should be written to execute client-side. This avoids unnecessary server traffic and latency to improve performance.

    Calling functions on page load

    To execute JavaScript functions automatically when the page loads, attach to the onload event:

    window.addEventListener("load", function() {
      // JavaScript code here
    });
    

    This technique is commonly used to initialize interactive page elements like accordions or tabbed navigation.

    Triggering scripts on user interactions

    For functions that require direct user input, attach scripts to events like click, hover, scroll, key down, and more:

    document.getElementById("button").addEventListener("click", function(){ 
      // Execute code on click 
    });
    

    This allows user actions to directly trigger dynamic page updates without needing to navigate between pages.

    JavaScript Best Practices

    Following Accessibility Standards

    Ensure custom JavaScript adheres to web accessibility standards through techniques like:

    • Keyboard accessibility for functions
    • Using ARIA roles for dynamic content updates
    • Semantic HTML elements underlying scripts
    • Labels and alt text for images

    These practices ensure site content remains usable for people requiring assistive technologies like screen readers.

    Optimizing Performance

    When used heavily, JavaScript can impact performance. Optimize scripts through:

    • Loading external .js files asynchronously
    • Minifying code by removing whitespace
    • Leveraging browser caching by versioning script files
    • Debouncing rapidly firing events like scroll

    Write efficient code to avoid blocking user interactions and reduce load times.

    Handling Errors Gracefully

    Robust JavaScript should anticipate and handle potential errors to avoid breaking site functionality. Techniques include:

    • Wrapping code blocks with try...catch
    • Checking for undefined variables and null values
    • Displaying friendly error messages for users

    Planning for errors creates reliable experiences accounting for unstable network conditions and user behavior.

    Example Scripts

    Fading Image Slideshow

    This script rotates background images on a SharePoint site, applying a smooth fading visual transition between each image on timers:

      let images = [
        "image1.jpg", 
        "image2.jpg",
        "image3.jpg"
      ];
    
      let fadeDuration = 1000; // ms
      
      let currentIndex = 0;
    
      function transitionImages() {
        $('#container')
          .fadeOut(fadeDuration, function() {
            $(this)
              .css('background-image', images[currentIndex])  
              .fadeIn(fadeDuration);
            
            // increment index
            currentIndex = (currentIndex + 1) % images.length;
          });
      }
      
      // Start rotation
      setInterval(transitionImages, 5000);
    

    Form Validation

    This script checks required fields on a SharePoint form before allowing submit:

      const form = document.getElementById("myForm");
      
      form.addEventListener("submit", validateForm);
       
      function validateForm(e) {
        let name = document.getElementById("name").value;  
        let email = document.getElementById("email").value;
        
        if (name == "" || email == "") {
          e.preventDefault(); // Stop submit
          
          alert("Name and email are required");
        }
      }  
    

    Dynamic Menus

    This script hides subnavigation when scrolling down, and shows when scrolling up:

    let prevScrollPos = window.pageYOffset;
    
    window.addEventListener("scroll", function() {
    
      let currentScrollPos = window.pageYOffset;
      
      if (prevScrollPos > currentScrollPos) {
        // Show nav on scroll up
        document.getElementById("nav").style.transform = "translateY(0)";
    
      } else {  
        // Hide nav on scroll down
        document.getElementById("nav").style.transform = "translateY(-100%)"; 
      }
    
      prevScrollPos = currentScrollPos;  
    });  
    

    Troubleshooting JavaScript in SharePoint

    Debugging with Browser Developer Tools

    All major browsers come with built-in developer tools to debug JavaScript. Press F12 to access tools like the Console and Sources panels. Features include:

    • Logging messages like console.log for inspecting values
    • Breakpoints to pause execution on a line of code
    • Watching variables to monitor value changes

    Use developer tools to efficiently test scripts and pinpoint issues.

    Identifying Conflicts with Other Scripts

    If a JavaScript error references an unexpected function or variable name, another script could be causing a naming collision. To isolate, systematically comment out sections of code until the conflict is uncovered.

    Namespacing variables is best practice to avoid overlaps between scripts from different sources.

      // Scope variables and functions under namespace
      const MYAPP = {
        settings: {
          enableFeatureX: true
        },
        
        enableFeatureX() {
          // function body
        }  
      };
    

    Fixing Issues with Incorrect Scope or Timing

    JavaScript code may fail due to issues with scope - where variables and functions are accessible in the file. Double check proper use of function or block scopes. Relevant keywords include var, let, const, function, () => {}, and this.

    Errors also arise with timing - the order of operations needed for code to work. Slow things down by using timers, delays, or browser debug tools. This reveals any inconsistent loading sequences or race conditions.

    Leave a Reply

    Your email address will not be published. Required fields are marked *