All js functions need in .js file if I use the RequireJs? - javascript

I want to use RequireJs in my project, but I found that I can't write the following code
<html>
<head>
</head>
<body>
<input type="button" />
<script>
// Use the jQuery
$(function() {
//some code
}
)
</script>
<input />
<input />
// I had added the jQuery in required shim and jQuery is working in RequireJs.
<script data-main="scripts/main" src="/scripts/require.js"></script>
</body>
</html>
There was an error $ is undefined, when the page was loaded.
I looked up a lot articles, but I can't solve it. How can I handle this? I don't want to move the sample js function to .js file.

As you wrote in your question:
All js functions need in .js file if I use the requirejs?
And with the definition of RequireJS:
RequireJS is a JavaScript file and module loader.
Using a modular script loader like RequireJS will improve the speed and quality of your code.
So doing such inserting inline <script> tags in your page is not a good idea.
However, in answer to your question, because RequireJS load the scripts asynchronously, so you don't know when jQuery will load, and you can not use inline scripts as old schools, you need to use define or require methods as George Reith wrote in the answer.

First things first $ means nothing in JavaScript but is used by the popular jQuery library. JavaScript !== jQuery.
Secondly assuming you have loaded jQuery via require.js you need to put your initial script tag after
<script data-main="scripts/main" src="/scripts/require.js"></script> as it is being called before require.js.
Thirdly require.js asynchronously loads files so you must wrap your code in the require() or define() tag with a list of dependancies so it only calls them once they have been loaded.
e.g.
<html>
<head>
<script data-main="scripts/main" src="/scripts/require.js"></script>
</head>
<body>
<input type="button" />
<script>
/*
RequireJS is asynchronous so you must wrap your code
in "require(["jQuery"], ...)" so it only calls it once
jQuery has been loaded. Each included script is available
to you as a parameter in the callback function.
*/
require(["jQuery"], function($) {
$(function() {
});
});
</script>
<input />
<input />
</body>
</html>
Your settings should look like this:
requirejs.config({
paths: {
'jQuery': 'path/to/jquery'
},
shim: {
'jQuery': {
exports: '$'
}
}
});

You also have to include jQuery. There is a whole manual page devoted to this on requirejs.org which should help you out.
Maybe what you want is also explained here. Taken from there:
require(["helper/util"], function(util) {
//This function is called when scripts/helper/util.js is loaded.
//If util.js calls define(), then this function is not fired until
//util's dependencies have loaded, and the util argument will hold
//the module value for "helper/util".
});

Require.js doesn't even implement $. Why are you even wrapping you function in $(..)?

Try moving your sample script tag after the requirejs script tag. Currently your sample function is executed before requirejs gets a chance to load jQuery.

Related

Unable to use jQuery in the javascript function that define in external js

::SOLVED::
I have an index.php and I define some JavaScript function for do some thing in this page. I use jQuery in this functions. When I put the functions in the index.php between tags all thing work good but I need to put this functions in external is file. When I do it and then import it in index.php, the js file load and the part that don't use jQuery, work good but the jQuery actions not work! I have put the jQuery before is in head of index.php. the jQuery load and I test it by simple alert. I tried to put $(function).ready() surrounding the js function and other time surrounding the function content but it doesn't work!
<script language='javascript' src="/js/jquery-3.4.1.js"></script>
<script type="text/javascript" language='javascript' src="/js/external.js"></script>
And external js file like this:
function doSomething(){
//some JavaScript code that work good
//some jQuery code that doesn't work!
}
Where is wrong?!
Excuse me for my stupid question!
First of all write better HTML code.
<script src="/js/jquery-3.4.1.js"></script>
<script src="/js/external.js"></script>
function doSomething(){
console.log("I'm executed");
if (typeof jQuery !== 'undefined') {
console.log(jQuery.fn.jquery);
} else {
console.log("jQuery library not loaded check your Network tab");
}
}
Then seems your jQuery not loaded check your network tab for loaded scripts.

Loading jquery in the last position

I offen heard that loading jquery as last element is a good idea because this way a web page loads faster. At the same time I have a script in the header which shows error:
$(document).ready(function () {// Uncaught ReferenceError: $ is not defined
...
}
Should I move jquery loader before the script or I need to change this script some way?
Your concrete issue stems from the fact that you execute statements that use jQuery (i.e. they execute $, which is a function in the jQuery library, also called "the jQuery function" because jQuery is an alias) before it is loaded.
True, it is typically recommended to load scripts last, but that still means the scripts have to be loaded in the correct order, with usually jQuery before your own scripts using jQuery.
If you really want to load your own scripts before jQuery for some reason, you need to defer its execution and have a third helper script to run it, e.g.:
// script.js
(function() {
function myLibraryMainFn() {
$('div').text('simulating work, utilizing jQuery');
}
window.myNamespace = {
run: function() {
myLibraryMainFn()
}
};
}());
<!DOCTYPE html>
<html>
<body>
<div></div>
<script src="script.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
// Run your script now:
window.myNamespace.run();
</script>
</body>
</html>
Always refer library file first(in your case jQuery), then use it next..For page load and performance add it before body end tags of your HTML

Conditional Loading of CSS files based on test condition in JQuery plugin

I'm looking for the best approach to conditionally load some files based on a specific set of conditions.
I have three CSS files and two javascript files which I'm currently loading like so:
<link href="core.min.css" rel="stylesheet" type="text/css">
<link href="add_regular.min.css" rel="stylesheet" type="text/css">
<link href="add_retina.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery-plugin.min.js"></script>
As is evident the fourth file is JQuery and the fifth is my JQuery plugin. Inside the JQuery plugin are a series of functions that are like tests e.g. isMobile, isRetina, isPhone, etc. However, let's focus on isRetina.
What I am trying to accomplish is as follows:
Load JQuery and my JQuery Plugin first
Use isRetina function inside my JQuery plugin to check whether the device has a retina display
Load core.min.css
Load add_regular.min.css if not Retina display, or load add_retina.min.css if Retina display
Currently I'm loading all three CSS files and I wouldn't want to do that because I've got a bunch of other CSS files and I want to load them as my JQuery plugin determines which one is best as per my above example. For example, I might have a phone.min.css that I would want to load after I do another test using my plugin's isPhone function.
I'm considering using YepNope and doing something like this:
<script type="text/javascript" src="yepnope.min.js"></script>
<script>
yepnope([{
load: ['jquery.min.js', 'jquery-plugin.min.js'],
test : $.myplugin.isRetina(),
yep : ['core.min.css', 'add_retina.min.css'],
nope : ['core.min.css', 'add_regular.min.css'],
complete : function(){
//my jquery plugin constructor here
$(selector).myplugin(options);
}
}]);
</script>
However, even if the above approach is the correct one, I am not sure how to implement document.ready, as my plugin's constructor needs to run only when the DOM is ready.
I would like some ideas on how I can pull this off using YepNope or any other solution.
Cheers.
I am not sure how to implement document.ready, as my plugin's constructor needs to run only when the DOM is ready.
There are two relevant events
window.addEventListener('load', function () {
// code runs when document+resources have finished loading
});
and
document.addEventListener('DOMContentLoaded', function () {
// code runs when document has finished parsing, but before resources loaded
});
If you wait for either of these events before importing jQuery, I'm not sure what effect it will have on jQuery's inbuilt $(document).ready / similar.
That said, you do have the option of checking document.readyState === 'complete' before attaching listeners, to see if you should invoke straight away.
I was just going over the JQuery Docs for .ready(), and apparently $(function(){}); is equivalent to $(document).ready(function() {}); (I'm not sure how I'm just discovering this #ScratchingMyHead).
I also saw this being used in a YepNope Tutorial on NetTuts+: http://net.tutsplus.com/tutorials/javascript-ajax/easy-script-loading-with-yepnope-js/.
So I guess my earlier code becoming what you see below should solve the problem:
<script type="text/javascript" src="yepnope.min.js"></script>
<script>
yepnope([{
load: ['jquery.min.js', 'jquery-plugin.min.js', 'core.min.css'],
test : $.myplugin.isRetina(),
yep : 'add_retina.min.css',
nope : 'add_regular.min.css',
complete : function(){
//my jquery plugin constructor added to JQuery DOM Ready Stack
$(function(){
$(selector).myplugin(options);
});
}
}]);
</script>
I will test this out and remove this if it doesn't work.
Not sure if I understand you correctly but this should work.
Include this by default:
<link href="core.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery-plugin.min.js"></script>
<script type="text/javascript">
yepnope([{
load: ['jquery.min.js', 'jquery-plugin.min.js'],
test : $.myplugin.isRetina(),
yep : ['core.min.css', 'add_retina.min.css'],
nope : ['core.min.css', 'add_regular.min.css'],
complete : function(){
//my jquery plugin constructor here
$(selector).myplugin(options);
//Remove the mask here.
}
}]);
// Feel free to call ready() here
$(document).ready(function(){
// whatever you want here
});
</script>
Then you can call ready() adding your specific logic according to the output of your tests. This way ready will only fire once the above has loaded and executed.

JQVMAP with requirejs

How do I use jquery vector maps with require.js as a module?
Is JVP amd compatible? It'll be great if someone could link to an example or suggest some workaround.
I can't use shim option as I'm using old require.js and can't update it.
You can wrap the library with a define yourself, effectively achieving what the shim option does. A quick test setup:
jqvmap-wrapped.js
// to simplify the example used jQuery named as "jquery.js"
define(['jquery'], function(jQuery){
// original jqvmap.js goes here
// (...)
// please note: not returning anything
});
index.html
<html>
<head>
<script data-main="index" src="require.js"></script>
</head>
<body>
<div id="vmap" style="width: 600px; height: 400px;"></div>
</body>
</html>
index.js
define(['jquery', 'jqvmap-wrapped'], function ($, _jqvmapEmpty) {
console.log('jQuery=', $);
console.log('jqvmap-wrapped=', _jqvmapEmpty);
console.log('jqvmap attached to jQuery? ', $.prototype.vectorMap);
$('#vmap').vectorMap({
// params
});
})
A word of explanation: the plugin adds itself to jQuery, it has no "standalone" version. The wrapper module doesn't return anything, it just has a side-effect of adding jqvmap to the jQuery object; that's why the _jqvmapEmpty variable itself is undefined. It's available through jQuery, though, so you can use it in the same manner you'd do it in a non-modular code.

Jquery - Linking external .js file not working

For some reason the external .js file I am linking to isn't working. I am linking to it like so:
<script src="jquery.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
I have tested jquery using a simple inline script to hide a paragraph of text when it is clicked on so the jquery library is present and working.
The jquery.js file is in the same folder as the index.php file that is calling it.
What am I doing wrong?
This is the code I have in the external .js file currently just to test it is working(it isn't):
$("document").ready(function(){
$("p").click(function(){
$("p").css("color", "red");
});
});
Problem 1
It looks like jquery.js contains the code you wrote that depends on jQuery.
You need to load jQuery before you try to use it.
Swap the order of the <script> elements.
Problem 2
$("document") will wait for <document> elements to be ready. HTML doesn't have such a thing. Lose the quotes to pass in the document object directly.
Better yet, forget about the explicit call to ready and just
jQuery(function () { /* your function */ });

Categories