Accessing a function from another javascript file - javascript

I have 2 Javascript files, a main.js which loads first and then a secondary.js which loads afterwards. What I am trying to do is create a global function in main.js which can be utilized on the pages where secondary.js is loaded.
Here's what I have in main.js:
var doSomething;
doSomething = function() {
//things to do
}
And then in my secondary.js:
var result = doSomething();
However, this is returning doSomething is not defined. I searched SO and found similar questions but was not able to find a solution that worked for me.

You are getting doSomething is not defined because doSomething is being created after secondary.js has been loaded, so it's not available and you are getting a reference error.
You need to control the order in which your code is getting executed.
How you accomplish this depends on how you are loading your JavaScript files. For example, let's say you are using script tags in your html file. You can have main.js load after secondary.js like this:
<script src="main.js"></script>
<script src="secondary.js"></script>

Related

React - Using external js from CDN

Sorry, I put this again since the old post got merged into some post that doesn't relate to my question ... I'm new to React and trying to convert a php website into react components. However, in old website there are some function in pure jquery and from CDSNJS. The external javascripts function are not binding well with my component and I cannot figure out how to. Please can anyone give me some advice.
Case 1:
I got a an external function like this:
;(function ($) {
/* Global variables */
var prty, flickr;
$.fn.flickrGallery = function(flickrID) {
//Defaults settings
var opts = $.extend({}, {
Key:prty.settings["Key"],
Secret:prty.settings["Secret"],
User:prty.settings["User"],
PhotoSet:flickrID,
Speed:400,
navigation:1,
keyboard:1,numberEl:1 });
//Setup
prty.Setup($(this), opts);
}; //End FN
prty = {
.... Internal code
};
})(jQuery);
And this is my component's code:
async componentDidMount() {
//$('#gallery').flickrGallery(2); // Not work
//const el = ReactDOM.findDOMNode(this.display); Not work
//$(el).vectorMap({map: 'world_mill_en'});
//$(el).flickrGallery(2);
//const el = ReactDOM.findDOMNode(this.domRef); Not work
//window.$('#addSupModal').modal('show')
//$(el).flickrGallery(2);
window.$(this.productIntro).flickrGallery(2); Not work
}
Every time I run, an error like this appears:
Unhandled Rejection (TypeError): window.$(...).flickrGallery is not a function
Case 2:
Beside the case above, I'm also using a lib from CDNJS
<!-- jQuery 1.8 or later, 33 KB -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Fotorama from CDNJS, 19 KB -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.js"></script>
I have tried including these links into index.html but the same error as above happens when I run ... Please help
Try to access the flickrGallery function via window.jQuery instead of window.$.
The plugin add the flickrGallery function to jQuery. In most of the time, jQuery should be the same as $. However, in some cases, multiple version of jQuery are loaded and jQuery may no longer be equals to $.
The following suggestions were told to be not solving the problem. I will keep them below in case someone find it useful.
It looks like your react component script is executed and rendered before the external scripts is being executed. There are many causes to it and one of the reasons is the ordering of your script tags.
In the document head, make sure the ordering of your script tag is as follow.
<script src="path/to/external/library.js"></script>
<script src="path/to/your/react/script.js"></script>
These script tags do not have the defer nor async attribute, suggesting they should be downloaded, parsed and executed in order. The external script is executed first.
In other cases, where there are defer, async, etc. attributes are in the script tag, you can understand the order of execution by reading this cheat sheet.
If you are using plugin which adds its functionality to some global variable, your bundler may tree-shake it away because it does not detect any usage of its exports and thinks the module is not needed. In this case, you have to add side effect import (Doc).
In your entry module, add this at the very top:
import 'some-jquery-plugin'

QuerySelector Not Working in Rails Webpacker

I have the following JavaScript loaded into Webpacker:
'use strict';
(function() {
alert("This shows up.");
var someObject = document.querySelectorAll('[data-toggle="thing"]');
})();
I know that the file is loaded into Webpacker correctly and is executed because I see the alert This shows up.. However, when I go into the console, someObject is an empty array despite the page containing an object with the data-toggle attribute.
I don't see any errors in the console to help diagnose the issue.
I am guessing that the problem involves the script executing before the page is loaded? However, I'm not sure how to remedy that situation when using Rails 6 with Webpacker...
Any assistance would be hugely appreciated!
You may need to wrap your code in an event listener callback that will execute when the DOM is loaded. This may be the case if your script tag is in the <head>; it executes before the rest of the page is loaded.
window.addEventListener('DOMContentLoaded', (_event) => {
let someObject = document.querySelectorAll('[data-toggle="thing"]');
});
You also don't necessarily need to wrap your code in an IIFE (i.e., (function() { })() because each file in webpack is (typically) treated as module with its own function scope.

How do I overcome a "function is not defined" error when loading an external .js file?

I'd like to create a JS plugin (with ES6) so that it can be called from an HTML file, like this:
<div id="emails-box"></div>
<script src="emails-box.js"></script>
<script>
const container = document.querySelector('#emails-box')
EmailsBox({container, ...options})
//some code
</script>
and it can be used independently.
What the EmailsBox will do is to take the container and add a children div with a box to store a bunch of emails.
I've tried to do this for 2-3 days, but everytime I try to load the .js file, I get a:
EmailsBox is not defined
I'm getting desperate. Could you someone give me some light? Thanks!
EDIT: In my emails-box.js file, I could have something like this:
var EmailsBox = function(obj){
console.log("EmailsBox called")
// some code
return true;
}
Worked fine for me. Make sure that emails-box.js is in the same folder as index.html and the name matches the one you're linking to. working setup
Most likely the file path of your .js file is referenced wrong. So first make sure that you referenced file right. If it is, then try to define function like don't assign it to variable, it might not be defined on load page.
function EmailsBox(obj){
// some code
}
And if you really need it assigned to variable try using ready function.
var EmailsBox = function(obj){
console.log("EmailsBox called")
// some code
return true;
}
<script>
(function() {
EmailsBox({container, ...options})
})();
</script>
When calling the function, make sure options variable is defined.
So that instead of calling:
EmailsBox({container, ...options});//when options is not defined,
define options first and then call the EmailsBox function like so:
var options = 'hello'; //for example
EmailsBox({container, ...options});
If your emails-box.js file is properly referenced, it should work just fine.
There is a good chance that the problem with your source but if its because its not loading which would be weird then try using js to load the script if this doesn't work its wrong for sure and you should check it is right
var source = 'source here to script file';
var script = document.createElement('script');
script.onload = function () {
//what you want to do with this script
};
script.src = source();
document.head.appendChild(script);

How to access objects in an external js file from another external js file

Hello fellow programmers,
I am wondering today how to access objects from another external js file. I'm using this as a way to organize my code throughout multiple js files. Here's an example of what I'm trying to say.
Imagine this as the code from an external js file:
$(function () {
function Person() {
this.name = "Bob";
}
})
And I want to access that object in another js file:
$(function () {
var person = new Person;
alert(person.name);
})
Is there a way to do something like that? How would I need to position the html?
My first wonder is why you have your JS wrapped in a function like so. You can see here I've accessed "hello" from another script loaded after it's set - as it's set in the global space.
https://jsfiddle.net/sj7bp97c/
<script src="https://pastebin.mozilla.org/?dl=8907696">
</script>
<script src="https://pastebin.mozilla.org/?dl=8907697">
</script>
One script sets the value, the other prints it to console. Unless it's required for your Javascript to be surrounded by functions, I'm not sure why you're doing so.
Reveal the function to the global scope:
$(function () {
function Person() {
this.name = "Bob";
}
return {
Person: Person
}
})()
When revealed to the global scope, you access it from within another JavaScript file as soon as the script has initiated. So you'll want to include it after you included this one.
You just need to mention both of your js script files in head section of html.
Javascript will take care rest of the things.
<head>
<script src="First.js"></script>
<script src="Second.js"></script>
</head>

Reassigning javascript function in an attached js file

I have an HTML page with multiple attached js files that include functions that are used on that page.
For functions that are included on the base HTML page they are successfully re-assigned. FunctionA = FunctionB.
The problem comes when I try to reassign a function that is part of one of the attached js files. The normal reassignment doesn't work. Say FunctionC is on attached js file more functions.js .
I try FunctionC = FunctionD. FunctionC runs as it would normally - WITHOUT the reassignment to FunctionD. I know the reassignment to FunctionD 'should' occur before the FunctionC runs because it fires when I check with console.log.
Any ideas as to why this isn't working would be appreciated.
You have to make your reassignments after included file.
For example (Disclamer: don't do this in real projects - this is for demo purposes only) the code below includes jQuery library, but then overwrites jQuery function with a custom one:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
jQuery = function(s) {
alert(s);
}
</script>
<script>
jQuery('aaa');
</script>
when this runs it produces alert (demo), but if you reverse the order of first two script tags - original "attached" jQuery function will take over.

Categories

Resources