load jQuery into a file via JavaScript? - javascript

I have an idea where I would like to load jQuery (via CDN) into a JavaScript file that when called on the page loads jQuery via the CDN and also loads the JavaScript file. so instead of doing:
<script>jquery</script>
<script>myscript></script>
I would just do:
<script>myscript</script>
and then jQuery would just load.... Because in the myscript.js I would be doing something like: call jQuery via CDN .... do js code here that uses jQuery ...

Although we can hope for a module solution in a near future, JavaScript currently doesn't allow for simple script dependency management.
You have a few solutions, the two main ones are :
you write in your code a script element
you use a library which manages dependencies like RequireJS
If you want to use RequireJS, then you'd better read the guide dedicated to importing jQuery.
Today, with the current state of the import management in browsers, I would generally recommend to be less ambitious and to simply import with a classical script element. But RequireJS is interesting and you might find it useful when your application grows.

Add this to your script:
document.write(unescape("%3Cscript src='/js/jquery-X.X.X.min.js' type='text/javascript'%3E%3C/script%3E"));

Related

import external js file in meteor project

I have a meteor project where I want to include the conversational form framework.
There is a npm package, however it is not properly imported (probably due to some kind of bug). According to the github issue, this:
import cf from 'conversational-form'
does not work, because the export function exports cf.ConversationalForm, not cf (but cf is needed for existing declarations). The form is created and styled, but cannot be addressed in the js.
I was already able to use the framework in a normal html/js/css project, so now I wanted to just include the external script as a workaround.
However, downloading + importing in client/main.js did not work for me.
I've tried:
import '/imports/api/conversational-form.min.js
as well as:
$.getScript
in Meteor.startup.
Do I need to write specific exports in the external .js? I'm far from a professional, so I'm a little hesitant to dissect the external .js.
Any tips on how to simply mimic the html-script-inclusion? Or other ideas on how to get the framework running?
Sincerely, desperate.
Well Meteor allows you many ways to do that, the first ideas that come to my mind are:
Depending on your project structure you can create your own meteor package as a wrapper and internally load the library.
Hardcoding the script tag in you entry point.(Im not sure if this would work to be honest but you can try).
I ended up downloading the script, modifying it to set my options and including it via \imports.
VERY hacky solution, but well, it works...
Meteor allow you to load external library and scope them in all the client
via the /compatibility folder.
Just put the file in there, and it will be scoped automaticaly.

Is it possible to wrap a JS file in a func without modifying the file?

I have a web application that uses Dojo, jQuery, and Bootstrap. This application has a "core" codebase of .js files that cannot be modified in any way.
I'm attempting to add an external service to the application that conflicts with jQuery's global usage of $. $ is used many times in the "core" codebase. Is there a way to wrap these core files in an anonymous function to locally define $ = jQuery without actually modifying the files in any way? Perhaps in the way they're defined/included in the project?
I'm aware of jquery.noConflict, but this would require I change the '$' reference throughout the "core".
You can wrap all of your jQuery code in an IIFE that allows you to use $ as jQuery inside but also use noConflict() so it doesn't conflict with the other library $
(function($){
// all your `$` code will work fine here and won't conflict with other library `$`
})(jQuery);
You will see most jQuery plugins written with this wrapper also for exactly the same reason
I asked my question in a very narrow and pointed way. What I was trying to accomplish was the isolation of .js libraries required for a new external service from the .js libraries in the existing application without modifying the files.
I've found that this can be accomplished by wrapping everything related to the new service in an <iframe>, where you're basically embedding another document with its own namespace in the existing document to isolate the libraries from each other. For example, you could add the following within a page:
<iframe>
<script src="...">
<script src="...">
[do stuff with above scripts here]
</iframe>
The global namespace in the iframe will be separate from that of the parent document.

Is there a way to provide multiple JS scripts within a single <script> tag?

I am building an app in JQM that has multiple instances but the same core of scripts.
Summarizing, every instance will have its own index.html initializing that particular instance with files both taken from the central repository (the common scripts/interface) and from the particular instance (files specific to that instance only).
Since I am adding more capabilities to the application, I need to constantly update the core of scripts with new addons (both 3rd party or custom scripts), but I don't want to go and update all the single instances with the new scripts I'm adding.
My question is: is there a method to include a <script> tag inside the index.html of every instance (say <script src="commonurl/commonscripts.js"></script>) and on my common repository, in the commonscript.js use structures like the java import, to import all the scripts I'm using?
I know it's not how js works, but the core of the question is: do you have any suggestion on how to keep the client unvaried and work just on the server side modifying just the included file, or anyway not having to manually modify the client index.html? Is js minification/merging my only option?
Same question applies to CSS files included in the client index.html.
Hope this makes sense, thanks for the answers!
You can do this with requirejs
RequireJS is a JavaScript file and module loader. It is optimized for
in-browser use, but it can be used in other JavaScript environments,
like Rhino and Node. Using a modular script loader like RequireJS will
improve the speed and quality of your code.
http://requirejs.org/docs/start.html

HTML5 Boilerplate: difference between script.js and plugins.js?

i can't find any definitive answer on the boilerplate docs, but can someone clarify the difference between plugins.js, and script.js? i'm a javascript newbie, and am tempted to just put all my scripts in one file... is there a good reason not to do this?
From the FAQ:
Script.js should hold your primary application script. It might make sense to store it in an object literal and execute it based on body classes.
Plugins I use for jQuery plugins and other 3rd party scripts myself. I put the jQuery plugins inside of the (function($){ ... })(jQuery); closure to make sure they're in the jQuery namespace safety blanket, especially if they were written by more amateur developers. See also jQuery Plugin Authoring.
in plugins.js file you get few helpers bundled, it's probably meant to include stuff you won't modify at all (or at least not so often), while script.js is a file ready for your... yes, scripts. ;)
what you said is true - in production, it's usually better to serve the browser one file instead of many. however in development it's easier to keep things separated.
that's the reason why boilerplate comes with a build script, which combines all your scripts into one so you don't have to worry about this.
in scripts -> your custom scripts
in plugings -> don't touch it!
In build process both files unite into one unique and compressed file...

How to include js file in another js file? [duplicate]

This question already has answers here:
Including a .js file within a .js file [duplicate]
(5 answers)
Closed 3 years ago.
How can I include a js file into another js file , so as to stick to the DRY principle and avoid duplication of code.
You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);
There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
I disagree with the document.write technique (see suggestion of Vahan Margaryan). I like document.getElementsByTagName('head')[0].appendChild(...) (see suggestion of Matt Ball), but there is one important issue: the script execution order.
Recently, I have spent a lot of time reproducing one similar issue, and even the well-known jQuery plugin uses the same technique (see src here) to load the files, but others have also reported the issue. Imagine you have JavaScript library which consists of many scripts, and one loader.js loads all the parts. Some parts are dependent on one another. Imagine you include another main.js script per <script> which uses the objects from loader.js immediately after the loader.js. The issue was that sometimes main.js is executed before all the scripts are loaded by loader.js. The usage of $(document).ready(function () {/*code here*/}); inside of main.js script does not help. The usage of cascading onload event handler in the loader.js will make the script loading sequential instead of parallel, and will make it difficult to use main.js script, which should just be an include somewhere after loader.js.
By reproducing the issue in my environment, I can see that **the order of execution of the scripts in Internet Explorer 8 can differ in the inclusion of the JavaScript*. It is a very difficult issue if you need include scripts that are dependent on one another. The issue is described in Loading Javascript files in parallel, and the suggested workaround is to use document.writeln:
document.writeln("<script type='text/javascript' src='Script1.js'></script>");
document.writeln("<script type='text/javascript' src='Script2.js'></script>");
So in the case of "the scripts are downloaded in parallel but executed in the order they're written to the page", after changing from document.getElementsByTagName('head')[0].appendChild(...) technique to document.writeln, I had not seen the issue anymore.
So I recommend that you use document.writeln.
UPDATED: If somebody is interested, they can try to load (and reload) the page in Internet Explorer (the page uses the document.getElementsByTagName('head')[0].appendChild(...) technique), and then compare with the fixed version used document.writeln. (The code of the page is relatively dirty and is not from me, but it can be used to reproduce the issue).
You need to write a document.write object:
document.write('<script type="text/javascript" src="file.js" ></script>');
and place it in your main javascript file
It is not possible directly. You may as well write some preprocessor which can handle that.
If I understand it correctly then below are the things that can be helpful to achieve that:
Use a pre-processor which will run through your JS files for example looking for patterns like "#import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)
If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.
Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.
JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( #import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".
Hope it helps.

Categories

Resources