Calling javascript function from Jquery - javascript

I am using AJAxsolr framework for building my search UI.
I have an index file which is an html file. This file has all the necessary script imports that import the javascript files. I have a javascript file script1.js which has a function as follows:
function myfunction(){
//Do the necessary stuff
}
I have another js file mywidget.js which is my custom widget. It has the following function:
(function ($) {
AjaxSolr.MyWidget = AjaxSolr.AbstractTextWidget.extend({
init: function(){
}
// and other functions
}
});
I want to call the function myfunction() in script1.js from the mywidget.js file. I tried the $.getScript() function but couldn't get to call the function.
Can someone help me on this please?
Thank you!

You need to load the script1.js file before the mywidget.js file (ie. place one before the other in the HTML).
From there you should be able to call myFunction with no problems.
If after this you're still having issues, you can use $.fn.myFunction() to extend jQuery's prototype. In essence by doing this you'll be adding functionality to jQuery.

Related

My JavaScript code won't run after jquery ajax call

jQuery code in a script1.js file
$(document).ready(()=>{
$.ajax({
method:"GET",
url:"someurl",
success :
(data,status,xhr)=>{
//Create some html buttons after I get the data
//I want to append the js file here(the JavaScript file adds some event functions to the newly created buttons.I know i can add the event listeners to the button directly here but for some reason I prefer to have the code in a separate js file)
//This does not work
$('head'). append('<script src="script_here"></script>')
}
})
})
JavaScript code in a script2.js file
document.addEventListener('DOMContentLoaded',ready)
function ready (){
document.querySelector('button').addEventListener('click',()=>{
//Do some other stuff
})
}
I have tried appending the script2.js file through the jQuery but its not working.
I do not want to have everything in one file for easy debugging, and I need to have both vanilla js and jQuery in my project.
If you just want to load an external js file after the ajax call. Then I will show you using in Pure JS. As I have encountered similar issue, so it might help you.
(data,status,xhr)=>{
const fileref = document.createElement('script');
fileref.setAttribute('type', 'text/javascript');
fileref.setAttribute('src',
'https://speechanywhere.nuancehdp.com/3.0/scripts/Nuance.SpeechAnywhere.js?_r=' +
(Math.random() * Math.pow(10, 18)).toString(32)); // the math random will help from cache errors each time you load
document.getElementsByTagName('head')[0].appendChild(fileref);
}
Import and use external JS Library

How do I add a personal script to an existing node.js library?

I have a local copy of the hls.js library and I need to include a personal script with custom functions in it.
How do I go about adding a new script to the library and how do I use the function written in the new script?
Let's say that I want to add a script called hello.js that contains a function that logs "Hello World".
When I call that function in my main.js I need it to execute.
Any ideas on how to do this?
Currently, I'm getting an error that the function is not defined.
I placed the hello.js script in the src folder of the library but this (as expected) doesn't seem to work.
It should be possible to add functions to the exported hls.js object.
Your custom-script.js:
var hls = require('hls.js')
hls.customFunc1 = function () {
}
hls.customFunc2 = function () {
}
on main.js:
require('custom-script')
// your code follows
Any other code would be able to use the custom functions by just require'ing hls.js.

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
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 loaded
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.
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...
});
});

Can I tell Javascript to call a method from another JS file?

In AppMenu.js,
AppMenu = function()
{
var scope = this;
}
Also noted:
Star.Bus.addEvent("AppMenu_StatSheet");
Star.Bus.on("AppMenu_StatSheet", scope.AppMenu_StatSheet, scope);
scope.registerApp("Exit Game", "AppMenu/images/exit_button.png", "AppMenu_exit", "");
Further down is a method
scope.AppMenu_StatSheet = function()
{
showStats();
}
I moved the location of the showStats() method to another js file, and I want the method to send its call there instead of where it originally was going. In Javascript, can I tell the program where to look to call showStats()?
EDIT Curiously, there is no AppMenu.html. I now believe that all of the html is dealt with by a main HTML file in the above folder.
If you include both Javascript files in your PHP/HTML page, the compiler automatically uses your showStats() function, even when it is called from file1.js and the actual function is located in file2.js.
As long as you include both files in your HTML page you'll be fine. Maybe load the file with showStats() before the other one.

Calling a JavaScript function outside of the js file

I have problems with calling a JavaScript function (which is inside of an object, in it's own .js file) from an other HTML page. In the code exsample I'll just use a simple Hello World function.
//.js file
window.addEvent('domready',function(){
var Site = {
//Here I have like three other functions
//This function I want to detect the browser version. I use MooTools for this
detectBrowser : function(){
if(Browser.ie){
//Then what ever content goes here
}
}
}
//I execute the other three functions here because they need to be called on every page
Site.dropdownmenu();
Site.accordion();
Site.lightbox();
});
I'm working with MooTools so I have wraped everything inside of the domready function.
Now, I want this cetect function to execute only at one page. I have tried somethink like this:
//In the HTML file between two script tags:
Site.alert();
That does'nt work. Any ideas?
If I execute it in the .js file it works fine. But I don't want it to execute at every page.
If you declare a variable with var in a function, the variable is local to that function and inaccessible from outside that function. To make it explicitly global, declare it as a property of window:
window.addEvent('domready',function(){
window.Site = ...
This isn't necessary for the code to work, it just makes it explicit for programmers that might read your code that Site is a global.
External Javascript files just execute code; the code doesn't know where it's coming from.
As long as your code runs after the external JS file, it will work fine.

Categories