Can't get snippet to run on page load

  • 2
  • Problem
  • Updated 3 years ago
  • Solved
Mostly because I don't know how :)

I have a script which works fine when pasted into the console, but I would like for it to run on Page Load.

var params = arguments[0],

    step = params.step,

$ = skuid.$;

var userModel = skuid.model.getModel('User'),
    user = userModel.getFirstRow(),
   weekUpdateModel = skuid.model.getModel('WeeklyUpdate'),
   weekUpdate = weekUpdateModel.getFirstRow();
var userAlias = user.Alias + ' Update - ' + user.Today__c;
weekUpdateModel.updateRow(weekUpdate,'Note',userAlias);
$.each(weekUpdateModel.registeredItems,function(){
  this.refreshFields();
});

Thanks,

Jacob
Photo of Jacob Flatter

Jacob Flatter

  • 1,512 Points 1k badge 2x thumb

Posted 5 years ago

  • 2
Photo of Rob Hatch

Rob Hatch, Official Rep

  • 44,006 Points 20k badge 2x thumb
You actually want this snippet to run AFTER page load,  because you need the model data to be available.  This is why it runs successfully from the console.  Models have loaded etc.  You need to wrap your snippet in a function that waits for the page to load before executing.  Somthing like this: 

(function(skuid){
var $ = skuid.$;
$(function(){
Your Function goes here......
});
})(skuid);

Actually if you create a new Javascript resource of type Inline you will get this code prepopulated for you.  
Photo of Jacob Flatter

Jacob Flatter

  • 1,512 Points 1k badge 2x thumb
Thanks Rob! Learning JS by sheer force is challenging sometimes.
Photo of Sharon Anoop

Sharon Anoop

  • 232 Points 100 badge 2x thumb
Hi Rob, This works fine for a page. But when i use this page as a popup in another, its not working. Can u please suggest a solution for it? Thanks!
Photo of Sharon Anoop

Sharon Anoop

  • 232 Points 100 badge 2x thumb
Thanks! Found the solution :)
Photo of Gary Bailey

Gary Bailey

  • 1,628 Points 1k badge 2x thumb
Page loading snippet
Photo of Irvin Waldman

Irvin Waldman, Champion

  • 9,006 Points 5k badge 2x thumb
(function(skuid) {    
    var $ = skuid.$;
    // Register a snippet to run
    skuid.snippet.registerSnippet('HelloWorld', function() {
        console.log("Go Skuid!");
    });
    // Called on page load
    function init() {
        skuid.snippet.getSnippet('HelloWorld')();
    }
    // Run the snippet initially on page load
    $('.nx-page').one('pageload', function() {
        init();
    });
})(skuid);