使用jQuery / javascript如何检查页面中是否已调用JS文件(SP.JS)?

我想检查document.ready中是否已加载特定的JS文件。

像这样的东西:

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

JS文件不是任何插件。

它基本上是一个与SharePoint相关的JS文件,如Sp.JS.

我们只知道文件名。

[更新 – 添加代码]

我添加了以下代码,它在控制台中抛出一个错误:SP.Runtime.js已经加载。

如果我删除SP.Runtime.js的加载,我的代码在默认情况下未加载Runtime.Js的某些页面中不起作用。

 $(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 // }); }); }); }); }); 

请建议。

谢谢

SharePoint JavaScript库,特别是SP.SOD命名空间包含用于加载/确保JavaScript文件的方法。

  1. SP.SOD.executeOrDelayUntilScriptLoaded – 如果加载了包含它的文件,则执行指定的函数,例如:

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

    在这种情况下,将在加载sp.js文件调用myfunc

  2. SP.SOD.executeFunc – 确保加载包含指定函数的指定文件,然后运行指定的回调函数,例如:

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

    该行为与前面的示例类似,但此函数还支持按需加载脚本的主要区别。

如果您只需要确保在执行代码之前加载SharePoint的特定本机JS文件,那么Vadim的答案就是您所需要的,但是如果您需要确保加载所有页面元素(包括所有JS文件),那么您应该使用window.onload

请看一下人们讨论windows.onload$(document).ready()之间差异的页面 。

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

更新:如果您在SharePoint中的任何页面中使用您的代码,那么您不需要强制加载本机JS文件,您只需要在页面加载过程的恰当时刻执行您的代码。 尝试使用$(window).loadwindow.onload而不是$(document).ready ,例如:

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