Including JS file in JS code - javascript

I have a requirement of including a .js file (more jQuery code) at a run time in a currently working jQuery script. For example, if my page gets authenticated, then I want to include a particular script file. I want to do this in ASP.Net MVC.
Is there a way to do this? If so, what path do I give when calling that file?
I googled $.getScript('file_path'); but my page is getting refreshed in a loop, I don't why! Maybe I'm doing something wrong in path.
Any help would be much appreciated! Thank you.

Try this Including a .js file within a .js file
Basically, create script tag, append it so that it is read before the one that requires it & load the needed .js

//Load JS files as following
["../common/howler.min.js","js/min.js"].forEach(function (src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.head.appendChild(script);
});

$.getScript() is exactly what you should use for this.
I want to call it in $.getScript();, what path should I give? like - "~/Scripts/content.js" or something else?
The issue there is because the tilde character (~) is an ASP.Net MVC construct which will not work in Javascript. For JS you need to use a relative path, for example:
$.getScript('/basefolder/foo.js');

Added correct path and it worked with "$.getScript();"

Related

How do I HTTP GET a .js file and extract 'exports' variables?

I am writing a site in Laravel to complement a game written in Node. It pulls information directly from the game's .js files stored on GitHub and the plan is to use Vue to generate some nice HTML to display the data.
The .js files are of the form:
'use strict'
let x = {...};
exports.x = x;
I can import the files using a PHP request (simply using 'file') and pass them to JS with either jQuery.getScript or axios.get (so far). However, I am having real trouble coming up with a way to extract the 'x' values here under exports. If I were writing a JS app in node, I would simply do the following:
var xFile = require('xFile');
var x = xFile.x;
However, I can't figure out how to do that here as both GET methods return a string, not a JS file. JSON.parse() doesn't work, and I would like to come up with a solution that doesn't just replace the non-JSON text as I would need a reusable solution for other files. I don't suppose anybody has any ideas?
Thanks so much!
You could try something like below.
you could create the script tag dynamically and attach the script in the body and add your javascript code using innerHTML.
You call this script in your ajax response code.
let script = document.createElement('script');
script.innerHTML = 'alert("Hi")';
document.querySelector('body').appendChild(script);
I managed to figure it out! It's a little janky, but you can run a node file in PHP with the exec command. I just wrote a node file to import the file and return the useful data. This probably isn't an optimal solution, but it works for me since I'm much more confident with JS than with PHP.

JavaScript and CSS dynamic versioning

I had a question regarding dynamic versioning of JavaScript and CSS file references in HTML files. For example:
script src = "test.js?v=1234"
And similarly with CSS references. I have done this in the past using ASP.NET, where I can call a function from the server side to generate a random number everytime the page loads ex:
"test.js?v=<%= myrandomfunc() %>"
I basically don't want the browser to get a cached copy of the css or js reference. I wanted to know if I can do this in JavaScript or jquery without using a server side language like asp or php etc.
Any help is much appreciated.
Thanks !
This is called file revving and it depends on what build system you're using. For Grunt, there's grunt-filerev, for Gulp, there's gulp-rev and gulp-filerev-replace.
If you don't yet use a build system, you might also want to check out Yeoman which will generate just about everything you need, including file revving.
I wanted to know if I can do this in JavaScript or jquery without
using a server side language like asp or php etc.
Yes.
var script = document.createElement('script');
script.onload = function() {
//do your stuff here
};
script.src = "http://whatever.com/the/script.js?v="+(+new Date());
document.getElementsByTagName('head')[0].appendChild(script);
Another option is to send the right headers :

Delay function call when dynamically loading javascript files

I am using enquire to dynamically load javascript files but hitting what I can only assume to be a loading priority problem since it works some of the time. Is there a way to hold off running a function until all files are loaded?
The relevent bit of enquire is
enquire.register("screen and (min-width: 564px)", {
match : function() {
loadJS('script/jquery.js');
loadJS('script/jquery.slides.min.js');
loadJS('script/TMSScript.js');
}
and the load function is
function loadJS(url)
{
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.head.appendChild(script);
}
The function I need to run is located at the end of TMSScript.js and it calls the jquery plugin so all 3 files need to be loaded in order for it to work. If I load all files in the header then the function will execute fine with a simple onload call in the body.
The idea is that a different method will be used on mobiles for my gallery (probably jquery mobile) and I don't want to load any unnecessary files.
Someone may correct me, but I believe outside of either loading these three in separate script tags placed in the correct order, or loading a single js file with these plugins concatenated in the correct order, you can't. Loading a src on a programatically created element now runs in an async fashion (in current browsers anyways I beleive), meaning you wouldn't be sure exactly when it's going to return back, and in what order.
It sounds like you want to use something like browserify or require.js which can help handle what you're trying to accomplish. I suggest checking out those projects.

How do I use Firebase in an external Javascript file

This is probably a very simple issue, but I've been trying to use Firebase in an external javascript file that is being used with an HTML file and can't get it to work properly. I am planning to use this file for many other similar pages, so I'd rather keep it in an external document. Specifically, my code is:
$(function() {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.src= 'https://cdn.firebase.com/v0/firebase.js';
head.appendChild(script);
var Database = new Firebase('https://myfirebase.firebaseIO.com/');
...
but when I try to run it, it says that the Firebase object/keyword is undefined. I know that the script is being correctly appended to the HTML page because I've checked the HTML on the page after running the code.
I have also read somewhere that you might need to have a personal server to run Firebase, but frankly I don't really know what that means - in any case, I use Mac OSX and run all of my HTML and Javascript in Chrome.
Thank you very much!
The problem is that using document.createElement does not force the script to be loaded and rendered before your inclusive script is invoked (it's being invoked now). There are no guarantees by this method on when the script you include will get invoked.
Additionally, you are loading the script onDomReady by putting it inside $(function() {...}); you would want to insert it into the header immediately, not wait for the entire document to load.
The simplest answer is to just put Firebase into the head of the html page; you haven't really explained your limitations here, but I assume this isn't an option for you. If it is, KISS.
Another simple answer is to utilize jQuery, since you obviously have it available.
$.getScript('https://cdn.firebase.com/v0/firebase.js', function() {
// now I can use Firebase
});
You can also accomplish this with other methods (wait until Firebase is defined using a setInterval; utilize other script retrieval methods besides document.createElement--try googling "load scripts dynamically via javascript load order"), but I think this covers your needs sufficiently.

How do you import multiple javascript files in HTML index file without the bloat?

Is there anyway of importing multiple javascript files in HTML without having to specify each file?
<script src="js/toolkit/Toolkit.js"></script>
<script src="js/toolkit/Viewable.js"></script>
<script src="js/toolkit/Overlay.js"></script>
ie. can I specify something like js/toolkit/* ?
I have 50+ javascript files that i have to import, and to specify each file seems very time consuming.
Including a JavaScript file in another JavaScript file is common in web development.
Because many times we include the JavaScript file at run time on the behalf of some conditions.
So, we can achieve this using JavaScript as well as using jQuery.
Method 1: Use JavaScript to include another JavaScript file
Add the following function in your web page.
function loadScript(url)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
head.appendChild(script);
}
just call the below loadScript function, where you want to include the js file.
loadScript('/js/jquery-1.7.min.js');
Method 2: Use jQuery to include another JavaScript file.
Add jQuery File in your webpage.
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
Just call the getScript function functions.
jQuery(document).ready(function(){
$.getScript('/js/jquery-1.7.min.js');
});
How to include a JavaScript file in another JavaScript File
There's a way:
You can create a javascript function that takes the path as a parameter and creates these HTML lines:
<script src="js/toolkit/Toolkit.js"></script>
<script src="js/toolkit/Viewable.js"></script>
<script src="js/toolkit/Overlay.js"></script>
And you'll just have to call this:
loadLib("toolkit/Toolkit");
loadLib("toolkit/Viewable");
loadLib("toolkit/Overlay");
But this is not recommended because the load time will be increased due to the number of HTTP requests.
You should better use something in the server side to put everything in the same file.
No you can't do it. And by the way this is not good idea to load all 50 separate files. Consider compressing them in one single script to improve performance and decrease page load time.
You can setup grunt to watch the folder of the scripts and concat/minify them into a single file, then you just have to include that in your HTML file.
You will need to specify each file for the browser to know what to retrieve, but depending on the IDE you are using, there may be shortcuts for doing this, (Visual Studios allows you to drag and drop script files into the html to add references).
During development, you want to do just as your doing by keeping the files separate for troubleshooting, but in production, as others have commented, its very good practice to minify your code and combine them into one file. That makes it only one call, and can reduce your overhead significantly.
I recommend you to use JSCompress. It will compress all your javascript code into one single javascript file.
import "./angular.min.js"
import "./jquery-3.6.0.min.js"
import "./app.js"
<script type="module" src="js/importJS.js"></script>

Categories