Using jQuery / javascript How to check if JS file ( SP.JS) is already called in a page?

限于喜欢 提交于 2019-12-06 04:33:16

SharePoint JavaScript Library, in particular SP.SOD namespace contains methods for loading/ensuring JavaScript files.

  1. SP.SOD.executeOrDelayUntilScriptLoaded - executes the specified function if the file containing it is loaded, for example:

    ExecuteOrDelayUntilScriptLoaded(myfunc, "SP.js");
    
    function myfunc()
    {
    }
    

    In that case myfunc will be invoked after sp.js file is loaded

  2. SP.SOD.executeFunc - ensures that the specified file that contains the specified function is loaded and then runs the specified callback function, for example:

    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', 
     function (){
         //your code goes here...
     });
    

    The behavior is similar to previous example but the main difference that this function also supports load on demand scripts.

Isaac E. Krauss

If you only need to ensure that specific native JS files of SharePoint are loaded before executing your code then Vadim's answer is all what you need, however if you require to ensure the loading of all page elements including all JS files then you should use window.onload.

Please take a look at this page where people discuss about the differences between windows.onload and $(document).ready().

window.onload vs $(document).ready()

UPDATE: In case you are using your code in any page within SharePoint then you don't need to force the loading of native JS files, you only need to execute your code at the right moment of the page load process. Try using $(window).load or window.onload instead of $(document).ready, by example:

$(window).load(function(){ SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function (){ context = SP.ClientContext.get_current(); //your code goes here... }); });

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!