Use Jquery inside JS file? - javascript

I have created an external JS file, this JS file contains some methodes that uses JQuery, i can't seem to find a way to refernece the JQuery file on JS file and user it there. Any help would be appreciated

Two things are important to reach your goal:
Include the javascript files. Include both files in your HTML via a script-tag, starting with jQuery to make sure it is loaded when used by your javascript.
Ensure jQuery. This is something way to less people tell you. If you write JS and jQuery for a long time, sooner or later you'll encounter a case where something is overwriting the $-variable. The $-variable is used by jQuery and everyone coding with it because of the obvious fact that it's just one char. However, jQuery doesn't have any "rights" or something for the $-variable, so basically anything or anyone could overwrite it. So I recommend your own javascript file looks like this:
(function($)
{
// your coding starts here.
})(jQuery);
You probably already encountered this when dissecting jQuery plugins from people who know what they're doing. It creates an anonymous function that takes one parameter which will be know by $ inside the function. The function is then immediately called and hands over the jQuery function. This way you can be sure that, whatever happens outside this function, inside of it $ stands for jQuery.

In your HTML file, include the jQuery file first and then your file:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="myfile.js"></script>

As long as you include the jQuery core in your HTML, the global jQuery object is available in any of your scripts. Is there a specific problem you're having?

You must write a piece of script (plain JS) that checks for the presence of jQuery, if not, it must append a script reference to the page pointing to a jQuery file (or Google CDN) to include jQuery. After that, you can use jQuery in the rest of your script.
I think it will involve some interval that checks wheter the jQuery object is present or not and waits with executing the rest of your code till that it the case.
Google for this, I'm sure there is something out there.

Related

Jquery - type error, is not a function

I am working on a widget that is embedded on a customers website, it loads a jquery file. however we need to detect if jquery is already loaded on a customers page to avoid conflicts and then not load our own jquery.
As a sidenote the widget works on all versions of jquery. The code being used is...
if (typeof jQuery == 'undefined') {
console.log("NOT LOADED");
scripts.push("https://d33f10u0pfpplc.cloudfront.net/perun/v1/js/widget/betaV2/jquery-1.8.2-min.js");
}
This works when tested locally, however when it was rolled out on some sites we got a ...
type error $tabs(...) is not a function
it seems that the jquery on the host sites must not have been fully loaded is my initial theory (could be wrong)
is there a way to improve the jquery detection used above? or if you know why it is not working i am happy to learn. thanks
First of all, $tabs is not a standard jQuery function. If it's part of a plugin, you need to make sure that's included as well.
Also make sure that jQuery isn't being run in noConflicts mode. In that case, jQuery may be defined, but not $.
Do you check the loading state of the browser? Javascript is typically executed at the time, when the browser is parsing it. Jquery is a bigger file and sometimes it will execute upcoming code first.
To solve it, verify that your own code is executed after dom is loaded:
$(function() {
// your code here
});
Alternative 2 is to check what
scripts.push()
exactly does. It needs to be asynchronous, just only add the file request does not ensure the file is loaded and parsed. Maybe this is your problem.
Using jQuery in widgets isn't optimal. Is it possible to write it in native js?
It's probably not help, but in example at http://www.initializr.com/
jQuery checked like
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.1.min.js"><\/script>')</script>
Please check your jquery version and your version not have a $tabs jquery function.
Then only you got this type error
$tabs(...) is not a function.
Otherwise try new version of jquery_ui file.

How/when/where to include external javascript

I'm looking for some advice on the best way to hold my JavaScript (jQuery) functions.
I am developing in MVC/razor and therefore have a layout page. I include my jQuery library and an external JavaScript file in here so it's available in every single page.
This is working well, but I am now becoming very aware of the fact that I am adding almost 300 lines of JS to EVERY page, where maybe half of that is used in any one of these pages.
One function is not in the external file and instead sits inside the HTML because I need to use variables set in my razor code.
I have a couple of questions around this arrangement:
Is placing JS inside the HTML generally acceptable when variables set using razor are used? There does not appear to be a clean way of passing a variable into an external js file
Should I split my functions down in to individual JS files and just include what is needed for each page in the site?
If I were to split them into multiple files, how would that work with jQuery's (document).ready ? Do I need to use that if all the JavaScript I am including is to be used?
I'm sure this will more a matter of opinion than a black and white answer, but I want to consider all my options before moving on. Even though it works fine as is, I can't help but feel there is a better/cleaner way.
Remember once a user lands on your homepage and loads the javascript file it will be cached in their browser so subsequent pages will not download the Javascript again.
I would definitely keep the js separate, you could have a snippet on each page that initialise the JS that that particurlar view needs. Put something like the below in the views that need to run JS
$(document).ready(function() {
mysite.mypage();
});
Then the function mysite.mypage() can be defined in the external JS file.
300 lines isnt the end of the world, I would say its probably too early to be worryign about optimisation.
You could always look at minifying that JS file to decrease the size. A quick and easy way to do this is here:
http://www.minifyjavascript.com/
Have you ever heard of require.js? http://requirejs.org/ I find it really useful.
It's a module loader so you are able to split all of your JS code into individual files and load only the ones you need on each page.
I don't know about passing a variable to an external JS file, I don't think its possible / the 'right' way.
You can make each external JS file into a function that accepts and returns parameters. Then in the page you need to use it:
- include the file dependancy
- call the function
Thats what I do, seems like your 2nd suggestion.
for the $(document.ready) question its really up to you. You don't have to use it but its useful for some things , check out this overview:
http://docs.jquery.com/Tutorials:Introducing_$(document).ready()

js alternative to jquery load method

I'm trying to throw together a single js file that includes the functionality of jquery's .load(), as well as the methods, in an effort to link only to a single js file, rather than both jquery and the load methods.
Instead of
<script src="jquery.min.js" type="text/javascript"></script>
<script src="load.js" type="text/javascript"></script>
this
<script src="load_including-necessary-js-for-load-methods.js" type="text/javascript"></script>
So basically I'm trying to extract only the necessary code from within jquery that makes .load() work and include it in the file with the load methods.
Suggest, instead, that you use something along the lines of html5boilerplate's jQuery call:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.2.min.js"><\/script>')</script>
Accessing it via the CDN ensures high-speed delivery of the jQuery code that is used by thousands of other pages/users on a constant basis,
... which also means that that code is most likely cached in your users' browsers ...
... which equates to highly-tested code that you're really not "paying for" in terms of overall load time. The second line, of course, allows you to offer a copy of it from your own site, in case the CDN has a hiccup, or you need to be testing offline (in which case, AJAX is borked for you any way you look at it, anyhow...).
OTHERWISE, check out the instructions on jQuery's Github: https://github.com/jquery/jquery#how-to-build-your-own-jquery and read up on building your own... they have instructions, there for excluding modules that you don't want from the library.
After that, you'll probably want to use some kind of bundling script to bundle all your JS (your custom jQuery build + your scripts) together, if you want to reduce everything to one call.
i don't know your reason why you cannot use all jquery library, but you still can write own js script and use onload or document.load, window.load its you reduce your code. If you need jQuery load() ... read and try to first comment of your question or use all small(own) jQuery library than waste of your time with this.

setting a source for all jquery in an application

Im new to Jquery but it turns out I used it quite a bit in my last application. My problem now is that its reloaded every single time one of my pages is loaded/reloaded. Is there an efficient way to reference it like we do a css or javascript file? for example:
<script type="text/javascript" language="javascript" src="js/behavior.js"></script>
I would really like to be able to do this with the jquery...because its quite a mess when you look at the source code. To avoid confusion: I already have jquery loaded. For example...this is already in my html:
<script src="js/jquery.min.js" type="text/javascript"></script>
What Im trying to cache is all of the code I've built off Jquery. For example:
$('#needDelete').slideDown('slow');
I have a bunch of these that need to be put into a file if that's even possible! Thanks!
jQuery is a JavaScript library. It consists of a single JavaScript file. All the documentation for it says to use <script src="..." to load it.
Update in response to edit:
The JavaScript you write that calls jQuery functions is still JavaScript and can be referenced from an external file just like any other JavaScript.
Yes, of course you can save your JavaScript code in a separate file (whether based on jQuery or not). Just keep your code separated and put it eg. in main.js file, then put a tag after jQuery script tag:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
Just for consistency and improved maintainability, it is easier if all the code is in one place than when it is often referenced within HTML like that:
show popup
Instead of the above you could do this in a separate JS file:
$('#a1').click(function(event){
event.preventDefault();
$('#popup').show();
}):
(of course the above code should be enclosed within onload or ondomready handler, so the code searches for elements after they become accessible - in case of jQuery and ondomready you can simply use: jQuery(function(){/* your code executed when DOM is ready */});)
I would refer jQuery from a CDN. This will allow the browser to do parallel download along with other resources from my domain, thus save some load time.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
The cdn version will be usually cached in your browser.
I don't get this question. What do you want?
I tried opening a file called custom.js. I dumped all of the jQuery
code into it and then referenced it. Nothing worked. Does there need
to be something additional in the reference page itself?
Why would you do that? You save some loading by decrease the number of different files, but the difference between one and two files is minimal.
Instead, do as Frederik Creemers suggested. Juse the jQuery-library at googleapis.com. The file is cached, meaning it will not load every single time a user visits your page. Only when the cache expires (not 100% sure how long this is). In addition, this library is used by many other sites, so you might be lucky and the user downloads it somewhere else and has it ready for use when going to your page.
Again, what you are asking (if I understood correctly) is pointless.
download jquery, and reference it like this:
<script src='jquery.js'></script>
Or, for an even better option, you can use google's cdn. This means that if a user comes to your site, and has already visited a site which uses the cdn, it will already have jquery cached.
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
and for the best option, to protect against the possibility of downtime of the cdn, combine the local copy and the cdn like this:
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script>
if(!window.jQuery){
script = document.createElement('script');
script.src='js/jquery.js';
document.head.appendChild(script)
}
</script>

Is there a good way to prevent jQuery from being redefined?

I encountered a problem that took me some time to debug where a plug-in that I was using for jQuery (in this case jFeed) was not working. The problem ended up being because we also used Amazon Associates product previews. The product previews code ends up including a number of other JS files through document.write(), including another copy of jQuery. Because the product previews code appeared below the jFeed script, jQuery was redefined without the getFeed function.
Is there a best practice to ensure that certain objects like jQuery only get defined once on a page? I'm thinking of something like #ifndef with C/C++, but I don't know how it would work in this case where I didn't write the code that dynamically pulled in jQuery again.
I think in your situation, it would probably be best to redefine the jQuery variable as something else. The other jQuery code might use a different version so you might want to define a new variable which would indicate which jQuery you're using.
You could so something like this:
<script>
var $jMain = jQuery;
</script>
You would then just use the $jMain instead of jQuery or $. It'll be up to you to you to ensure you have the correct jQuery object when you do this. Here's the documentation.
Unfortunately the environment inside one JS sandbox (like within a window or frame of a browser) was not really designed to support the modern world of pulling in scripts from various places; there's no way you can say "define this object and make it resistant to redefinition". (You can even redefine most of the Javascript built-ins if you try!)
Your best shot is to make sure that your code is eval'd last, which gives you final say over the state of the environment when it runs. That doesn't mean other code can't come along later and clobber your definitions, but that's generally really bad form. You can do this by having your script tag be the last element in the body of the document, for example.
See also this jQuery method, which won't help you directly, but gets you thinking about some solutions to page sharing: http://api.jquery.com/jQuery.noConflict/

Categories

Resources