Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to check if a particular JS file is already loaded in document.ready.

Something like this:

if(file already called/loaded) { // my code }
else {//some other code}

The JS File is not any plugin.

Its basically a JS file related to SharePoint like Sp.JS.

We just know the file name.

[Update - Added the code ]

I have added the below code and it throws an error in console : SP.Runtime.js is already loaded.

If I remove the loading of SP.Runtime.js my code doesnt work in some pages where Runtime.Js is not loaded by default.

$(document).ready(function() {
    var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
    $.getScript(scriptbase + "init.js",
    function() {
        $.getScript(scriptbase + "SP.Runtime.js",
        function() {
            $.getScript(scriptbase + "SP.js",
            function() {
                    $.getScript(scriptbase + "SP.Taxonomy.js",
                    function() {
                        context = SP.ClientContext.get_current();
                       // My custom function //

                    });
            });
    });
    });
});

Please suggest.

Thanks

like image 471
user2598808 Avatar asked Dec 08 '25 09:12

user2598808


1 Answers

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.

like image 144
Vadim Gremyachev Avatar answered Dec 10 '25 00:12

Vadim Gremyachev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!