I presume that inline JavaScript bound to orerror, onclick, ... run.
But would a <script type="text/javascript">...</script> element run javascript as well when wrapped with $(...) ?
If it does run is it sand-boxed?
Sorry for the misunderstanding:
Wanted to make sure that JavaScript loaded within the $ method would NOT run. I'm aware of other methods on how to load JavaScript scripts within the page and I generally use require.
Just wanted to figure out how much of a security risk wrapping HTML (containing script tags) within $ could be.
If someone can give me some insight/directions on how JavaScript is interpreted within the jQuery method that would give me my answer thanks.
Thanks :)
You always need to write
<script type="text/javascript"></script>
or
if you use the html5 Doctype
<script></script>
when you want to execute Javascript. in your html files.
If you want to execute javascript without writing these tags then you need to add a extern .js file and link to that file like this:
<script src="pathtofile/javascript.js"></script>
Friend please excuse me if my understanding of the question was wrong.
if you wrap some code in $() it will consider it as either the javascript or jquery code. But as we know script is a tag not a javascript code, so finally it will be throwing an error.
In order to execute any code which is in script tag, please place the code in a file and use getScript() function of jquery by enclosing in $(). Finally your requirement might be met :).
$(function() {
$.getScript(pathoffile);
});
Related
new to this stuff, please bear with me.
I have an external js file, declared in my HTML etc. JS code is fine and works in Fiddle - https://jsfiddle.net/0hu4fs4y/
<script src="js/noti.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script src="js/jquery.flexslider-min.js"></script>
<script src="js/scripts.js"></script>
However, it doesn't work. Am I running an old JQuery Library?
Is it something stupid/obvious I'm missing?
Two things:
I'm guessing noti.js relies on jQuery. If so, it should be after the script tag that includes jQuery (probably down with your scripts.js).
Make sure these script tags are at the end of the HTML, just before the closing </body> element, so that the elements they act on exist when the scripts run.
Your code works in the fiddle because you've pasted the code directly in and used jsFiddle's (mind-numbingly surprising) default that waits to run your code until the window load event runs, which is very, very late in the page load process. If you're a beginner, you've probably seen the anti-pattern of putting script tags in head and done that in your stuff, meaning that your elements don't exist when your code runs, because the parser hasn't seen them yet.
the console error at jsfiddle is:
ReferenceError: $ is not defined
which could be becasue your noti.js is using jquery
put jquery script on top of all other script
Hi I'm experiencing some problems including a javascript file in my html project.
When I include it like this at the end right before the body tag my site does not work correctly.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</body>
If, however i delete the tag at the end to make it look like this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"/>
</body>
everything works fine.
And if i include it within the head, it also works, independent of the syntax.
Why does it behave like this?
Do what everybody else has said, regarding the <script src="..."></script>
Use just src="//...", instead of src="https://..." or on non-encrypted pages (http vs https) your visitors will get security warnings for mixing the two protocols
If you have written jQuery code anywhere on the page, prior to actually including the file, you're going to get reference errors, where JS will not be able to find the function ($) you're trying to use.
There is a debugger available if you use Chrome, and press CTRL+SHIFT+J : it will take you to the developer-console, where I'm sure you're going to see all kinds of reference errors.
In Firefox, it would be CTRL+SHIFT+K, in IE it's F12.
This works under the same premise as writing in other languages where you try to use libraries or other classes, but don't actually import them until the bottom of your program.
For browser compatibility, you must use the first form:
<script src="https://..."></script>
with an explicit closing tag </script>. If this is the case where your code is not working, then your real problem lies elsewhere and not in the way you close the tag.
There might be some race condition happening for you... it will be good if you can provide complete code... if you attach that in header ... then your jquery is successfully loades and then executes your body part... if your attaching that in body ... then closure of script is give some issues... try to play while changing your script code placements in you body tag.
</script> closing is compulsory to work in cross browsers
This might help you in ur debugging.
Why do you want to load jquery in the end of your code? If you have some other scripts that need jquery, then they should be loaded after it. So either you put all script tags in head or in the end of body — jquery should be loaded before other files that depend on it.
I have an external javascript that contains something like:
document.writeln("<script type='text/javascript' src='...'></script>");
In the original html i have something link
<div id="banner">
<script type="text/javscript" src="<the external javascript above>"></script>
</div>
How can i load that delayed?
I've tried using window.setTimeout and append that javascript but its not working.
Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
Thank you.
You can call your injection code on window.onload.
window.onload = function() {
inject();
doSomethingElse();
};
window.onload will wait until all assets have finished downloading, such as images and scripts. After scripts are downloaded, you can inject your code to page.
Maybe a better way to do it would be to add a delay to the script.
Also, if you use something other than 'document.writeln' for example:
$('#banner').append(...);
you can better direct where it goes.
There is an open source javascript library for doing this kind of thing: http://labjs.com/
I have used it in the past and it worked very well.
Its important that the javascript to be loaded inside that div so the document.writeln executes in the right place.
That is not entirely true. Especially if the div is empty you could simply use: document.getElementById('banner').innerHTML = "<h1>HTML-Output here.</h1>"
Bukko's answer would work as well if you are using jQuery. My answer is pure Javascript. With this newfound freedom you should be able to simply put the loading of your script at the bottom of the page or use a custom body.onload() function
Edit: or simply follow Samet's suggestions in conjunction with the .innerHTML. Hope this helps.
i am building a website using asp.net mvc and jquery.
as a best practice its known that including javascript should be done at the end of the html page.
so i basically include jquery.js and other js files in the end of the html before the /body tag.
now i have some controls which are included in the page as partials. and they need to add functionally to $(document).ready.
but i write the code as a script tag in the partial then the jquery library wont be even included at that time and i cant include this javascript at the end of the html from within the partial. since the partial is included in the middle of the html.
Move all javascript in single file(you may exclude jQuery file) and move it to the bottom.
If you are talking of good practice then, then writing inline javascript is not a good practice too.
So I would suggest move all your java script to single file,there are many tools available that merge multiple javascript files and crunch them, use those!!
Edit1
You may try this:
//define this at before body (or at the beginning of body)
var arrReadyCollection = [];
Inside controllers:
arrReadyCollection.push(site.module.Dialog_AcceptChanges);
arrReadyCollection.push(some_thing_Else);
At the end, after jQuery file
for (i=0;i<arrReadyCollection.length; i++)
{
var fn= arrReadyCollection[i];
$(document).ready(fn);
}
Note: this is not recommended way, its just way you can solve your problem
You should use a javascript loader like LABjs.
You can use it to run javascript when certain libraries are loaded and run.
<head>
<script src="lab.js"></script>
</head>
<body>
<script>
// $LAB uses async loading, no need to deferr to the end of body
// keeping a reference to the $LAB deferred is important, so we can
// use it from within partials (see below)
myPage.$LAB = $LAB
.script('someScript.js')
.script('someOtherScript.js')
.wait(function () {
// your scripts are loaded!
});
</script>
</body>
In your partials you can hook into LABjs, eg like this:
<script>
myPage.$LAB.script('jQuery.js').wait(function () {
// jQuery was loaded!
// if jQuery was loaded already by another partial or your main layout
// it will not be loaded again, but the callback will fire immediately!
});
</script>
That beeing said you really should follow the advice given by Praveen and tie your javascript files up as much as possible. Each request to your server will cost time and decrease the responsivness of your website.
Either fix your "control" files so that they don't require inline JavaScript, or else include jQuery at the top of the file.
You could also write a small "$" function of your own that you'd include before jQuery (and at the top). However, you'd be better off fixing those controls anyway.
Another possible solution would be to add a script tag dynamically from within the partial. This however could get messy if you want to run more than a few lines of code, eg:
<script>
var script = docuement.createElement('script');
script.innerHTML = "$(document).ready(function () { doSomething(); });";
document.body.appendChild(script);
</script>
This should run after the jQuery (which should be already somewhere at the end of the body) was loaded and run.
UPDATE:
This does not work, I assumed that inserting script elements in a DOM that wasn't ready yet wouldn't execute before the DOM is ready.
Use CDN's and quit obsessing about doubtful optimization. From the excellent jQuery in Action book, sec 1.22
NOTE For performance reasons, script blocks can also be placed at the bottom
of the document body, though modern browsers make the performance
difference rather moot. The important concept is to avoid embedding behavioral
elements within the structural elements.
I have the following line of code:
$('#text').append('<h2 style="color:white">afdghadfg</h2>');
If I paste this code inside of a script tag in the html, it works fine. However, when placed inside a .js file it does nothing.
Know that the .js file has plenty of other working javascript and jQuery code, it is only this line that won't work.
Try this in your JS file:-
$(document).ready(function(){
$('#text').append('<h2 style="color:white">afdghadfg</h2>');
});
Could be the context you are putting it. Make sure it's not wrapped in a function and directly executable. Also check the JavaScript console (Firebug / CDT) to see if there are any errors.
Another thing to check is if it's getting executed before DOM ready, but I can't really tell you without seeing more code.