问题
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
回答1:
SharePoint JavaScript Library, in particular SP.SOD namespace contains methods for loading/ensuring JavaScript files.
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 loadedSP.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.
回答2:
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...
});
});
来源:https://stackoverflow.com/questions/29793475/using-jquery-javascript-how-to-check-if-js-file-sp-js-is-already-called-in