This question already has answers here:
How do I include a JavaScript file in another JavaScript file?
(70 answers)
Closed 6 years ago.
I have a bunch of JavaScript links at the bottom of one of my HTML template. I want to create a separate JavaScript file that will only contain all the source links in it.
So instead of cluttering my template footer I want all the links in one JavaScript file. How can I achieve that?
What I'm really asking is how I can get a similar effect as the CSS #import functionality for JavaScript.
And if that is not possible can I place a block of HTML at the footer of my template from a different HTML file?
You could do this with ajax but an easy way is to just append them with jquery
$('.div').append('<script src="myscript.js"></script>');
hope that helps
You can create a seperate js file and a object in it. This object can have multiple keys and their value will these links. Return this object from the file
Hope this snippet will be useful
linkFile.js
var AllLinks = function(){
var _links ={};
_links.keyOne ="link1";
_links.keyTwo ="link2";
return {
links:_links
}
}
Also include this file using script tag
In other file you can retrieve this value as
AllLinks.links.keyOne & so on
Have an array that holds the link to your script files and then you have two options either to use $.getScript() to load each one Or by building an HTML out of it and appending it to your head or body tag. I prefer head tag to keep all the scripts and css files.
Your array of script files
var JsFiles = ["script1.js","script2.js","script3.js","script4.js"];
First approach using $.getScript()
JsFiles.each(function(i,v){
$.getScript(JsFiles[i], function( data, textStatus, jqxhr){
console.log( textStatus ); // Success
});
});
Disadvantage of the above approach is that the getScript makes a async calls to your script files that means if the script2.js is dependent on the script1.js (for example if script1.js is some plugin file which use initialize in script2.js) Then you will face issues.
To overcome you might have to then use Promises or write a callback on each getScript success function which will trigger next script load and so on..
If the order of the script loading is not important then above approach is good to go.
Second approach by building HTML
var scriptTags ="";
JsFiles.each(function(i,v){
scriptTags += "<script src='"+ JsFiles[i] +"'></script>";
});
$('head').append(scriptTags);
Good thing about this approach is that the script files will now load synchronously and you will not face the dependency problem. But make sure the independent files start from first and the dependent files come at last.
Related
I'm trying to call a function from my html: tasks-div-upload.html to my other html: task-tareas-actualizadas.html.
I'm including my scripts on the script tags of the html files
I tried to call the function like this
First of all this is the html that calls the function: tasks-divs-upload.html
and the function is in task-tareas-actualizadas.html
I tried to call the function like i do in java that is
writing the class and then the function, for example: people.countPeople(5);
In this case, there are not classes because its an html file so what can I do?
//tasks-divs-upload.html
function contadorTareas(){
for(var x = 0; x < divs; x++){
var numeroTareas = x;
}
prueba(numeroTareas); // <---------
}
//task-tareas-actualizadas.html
function prueba(numero){
console.log(numero);
}
Console shows this error "Uncaught ReferenceError: prueba is not defined"
This CAN be done but is mostly a bad idea and is not very common and has some specific requirements. It is best it NOT be done unless the user is aware of the interaction.
IF your task-tareas-actualizadas.html opens tasks-divs-upload.html in a new window then tasks-divs-upload.html can call window.opener.prueba() BUT, if the first window gets closed, it will not be there and they must both be of the same origin.
This interaction can also go the other way if the parent keeps a reference to the child window.
Better to create a JavaScript file say "myfunctions.js" that includes the functions you wish to use and include it in both pages UNLESS for some reason you need/want the pages to interact - say the child page alters the parent page DOM or some such.
Reference https://developer.mozilla.org/en-US/docs/Web/API/Window/opener
and https://developer.mozilla.org/en-US/docs/Web/API/Window/open
Well scripts in HTML are JavaScript code. They need to be either defined in separate .js files or included in html using <script> tags.
It is not possible to define a JavaScript function in a html file and then use it in another html file. You need to define the function is a separate JavaScript file and then include this file in the html page.
You may also use JavaScript modules which are natively supported by modern browsers.
I know this is a very basic, very newb question, but i cant seem to make it work.
I have 2 different javascript documents, one named movies and the other named calculator.
I would like to call calculator.js function, and put it inside my code in movies.js so that it would display it's result inside.
My code in movies.js is like this:
function formatState (movies) {
if (!movies.id) { return movies.text; }
var $movies = $(
'<span><!--CALL JS. FUNCTION HERE--> ' + movies.text + '</span>'
);
return $movies;
};
my calculator.js
function calculate_price(value) {
//some data
}
at the end display result would be something like: 39.99€ star wars
Any help is appreciated!
This isn't as basic of a question as you might think, because JS doesn't really have a clear pattern for this.
Check out the answer to this question.
Javascript does not support the concept of "includes" or "imports". If you want to do something like this you either:
Reference both .js files in your HTML page - the order in which they are loaded is important.
Use another library to help you with dynamic loading a Javascript file before executing any code. Require.js is an alternative. jQuery has a way to allow you to do this, but you will introduce another dependency...
More details here: How do I include a JavaScript file in another JavaScript file?
This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 7 years ago.
In html page, I'm include js
<script src="/script/lib.js?file=bootstrap,jquery"></script>
And in lib.js, I can include like this:
if(file=="jquery"){
$.getScript("//cdn.optimizely.com/js/jquery.js");
}
if(file=="ecomotion"){
$.getScript("//cdn.jsdelivr.net/emojione/1.3.0/lib/js/emojione.min.js");
}
if(file=="bootstrap"){
$.getScript("//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js");
}
ect
How can we do that?
You can't pass parameters to JavaScript files, like that.
You could, however, do this:
<script>
window.file = ['bootstrap', 'jquery'];
</script>
<script src="/script/lib.js"></script>
In your script:
if(window.file.indexOf("bootstrap") !== -1){
// Same for the other file types.
The disadvantage here is that you're creating a global variable, which is arguably a bad idea.
The advantage is that you can easily specify a list of files to include, while working around the fact that it's impossible to pass query strings to a JS file.
OPTION 1
The only way that you can really do this like you have written is if lib.js was interpreted on the server side. For instance in PHP (or Node, or .Net) you could then read the GET and spit out the appropriate $.getScript blocks as output.
Pros are that it'll work without any weird hacks. You could even work to make the file cache-able.
A simple .htaccess mod-rewrite can direct calls to libs.js to a PHP script.
OPTION 2
Another option would be to expose a function from libs.js that would initialise the includes:
libs.js
function getMyScripts(scripts){
/* loop through the `scripts` array and spit out
the `$.getScript` calls */
}
You page would then do this:
<script src="libs.js"></script>
<script>
getMyScripts(['lib1', 'lib2']);
</script>
I need to include a JavaScript object (JSON) in my HTML page.
JSON is rendered at the same time page HTML is rendered on server. Data is not retrieved using AJAX call.
I can think of two ways of doing this, and looking for feedback and recommendations.
What are good practices for passing JavaScript (JSON) blob with a page?
Option 1
HTML:
<script type='text/javascript'>
var model = { <JSON> };
</script>
.js:
function doSomething() { <use this.model here> }
Option 2
HTML:
<script type='text/javascript'>
loadModel({<JSON>});
</script>
.js (included at the top of the html file):
var model = null;
function loadModel(model) { this.model = model; }
function doSomething() { <use this.model here> }
Variation
Instead of including JSON in HTML, JSON can be stored in a separate .js file. Any comments on doing so?
Option 1 lets you include .js file anywhere, and including it at the bottom of the page makes it render faster (good thing), but since JavaScript renders the model on the page, this makes it a moot point. Still not depending on the location of the .js inclusion makes it less error prone.
Also R# complains (reasonably) about model being uninitialized.
Option 2 feels better (it encapsulate details better, for one), but .js must be included before call to loadModel.
I have seen and done both ways, but didn't notice any significant advantages of one way over the other.
Server platform should be irrelevant, but it is IIS 7.5/ASP.NET MVC 3/Razor
Forget your two suggestions - both are extremely vulnerable to XSS. NEVER PUT UNTRUSTED TEXT IN A SCRIPT TAG.
Instead, use the owasp recommendation.
Stick your (HTML encoded) JSON in the DOM like so:
<div id="init_data" hidden>
<%= html_escape(data.to_json) %>
</div>
Then read it in JavaScript like so:
// external js file
var dataElement = document.getElementById('init_data');
// decode and parse the content of the div
var initData = JSON.parse(dataElement.textContent);
There would be ever so slightly more overhead with option two. As you have the overhead of a function call, and an extra variable (your parameter), which will be allocated and deallocated.
As you said, there is little advantage/disadvantage to either way.
Can you use jQuery? Then you can use the DOM ready event instead of including javascript in your HTML.
EDIT:
Hmm, in that case you could include the JSON inside a hidden element when the page is generated. Then inside the DOM ready event you could read and parse it from the page using jQuery.
Another alternative might be to use HTML 5 data attributes and including the data in one of those.
If it were me I'd probably just use an ajax call since it is easier and seems a little cleaner.
I have a javascript function I'm writing which is being used to include an external JS file, but only once. The reason I need such a function is because it is being called when some content is loaded via AJAX and I need to run page-specific code to that content (no, just using .live won't cover it).
Here's my attempt, shortened for brevity:
$.include_once = function(filename) {
if ($("script[src='" + filename + "']").length === 0) {
var $node = $("<script></script>")
.attr({
src : filename,
type : "text/javascript"
})
;
$(document.body).append($node);
}
};
This works fine: the function is called, it loads the external file, and that file is being run when loaded. Perfect.
The problem is that it will always re-load that external file: the query I'm using to check for the presence of the script always finds nothing!
When debugging this, I added some lines:
alert($("script").length); // alerts: 4
$(document.body).append($node);
alert($("script").length); // alerts: 4
Looking in the dynamic source (the HTML tab of Firebug), I can't find the script tag at all.
I know that I could maintain an array of files that I've previously included, but I was hoping to go with a method such as this, which (if it worked), seems a bit more robust, since not all the JS files are being included in this way.
Can anyone explain the behaviour seen in this second snippet?
jQuery is a bit of a dumb-dumb in this case; it doesn't do at all what you'd expect. When you append($node) jQuery does this:
jQuery.ajax({
url: $node.src,
async: false,
dataType: "script"
})
Woops! For local files (eg on the same domain) jQuery performs a standard XMLHttpRequest for the .js file body, and proceeds to "eval" it by a whole convoluted process of creating a <script> tag (again!) and settings it's contents to your .js file body. This is to simulate eval but in the global context.
For cross-domain files, since it cannot perform the standard XMLHttpRequest due to the same-domain policy, jQuery once again creates a <script> element and inserts it into <head>.
In both the local and cross-domain cases above jQuery finally gets around to doing this:
head.removeChild(script);
And booms your .length check! Bummer.
So on to your problem, don't bother jQuery with this. Just do
document.getElementsByTagName('head')[0]
.appendChild(
document.createElement('script')
)
.src = filename;
Which will do what you'd expect, particularly wrt querying for it later.
You're trying to solve a problem that has already been solved several times over. Try LazyLoad for example. There are also similar plugins for jQuery.
Instead of setting the source attribute of the script-tag, set the "text" attribute of the script tag. This works in all modern browsers (the application where I use that in practice does not support IE6, so I do not know about this creep...).
In practice it would look like this (you HAVE TO add code to omit double inclusion on yourself - e.g. a simple array of all alread loaded scripts, though thats very application specific, and why should you anyway load code twice? try to omit double-loading code...!):
var script_source_code_string = <some dynamically loaded script source code>;
var $n = $("<script></script>");
$n.get(0).text = script_source_code_string;
$(document.body).append($n);
Or even simpler (without jquery, my code at this stage does not know jquery, it may also be loaded dynamically):
var script_source_code_string = <some dynamically loaded script source code>;
var s = document.createElement('script');
document.getElementsByTagName('head')[0].appendChild(s);
s.text = script_source_code_string;