Raw Github js file not loading (direct link) like CDN - javascript

I created a coding library for the public to use by putting a <script> tag in the <head> tag on the page but when I try to use the a function it says undefined when it ran.
. I linked the url to the index.js file but it doesn't load it to the client user.
<head>
<script src="https://github.com/McJoe21/coderslib/blob/master/index.js"></script>
</head>
When I run a console.log(ranInteger(1,10)) which I have defined in my index.js file but I get a ranInteger is not defined error. All help is welcome!

Technically speaking, GitHub doesn't allow source code to be accessed from their site like a CDN, however from This StackOverflow Question, there is a workaround. I wouldn't recommend using it, but you can use "https://cdn.jsdelivr.net/gh/" to get your script to work (from user #anayarojo on StackOverflow).
The url in your case would look like this:
https://cdn.jsdelivr.net/gh/McJoe21/coderslib/index.js
The pattern for the URL is:
https://cdn.jsdelivr.net/gh/<username>/<repository>/<file>

You cannot load JavaScript from raw version of Github because the content type(MIME type) is text/plain, not application/javascript or text/javascript. This is to stop you using Github as a CDN. Still you can achieve serving raw file as cdn in the following way, using cdn.jsdelivr.net.
https://cdn.jsdelivr.net/gh/<github-username>/<github-repo-name#branch-name>/<filename>
If file is at main branch, no need to include in branch section after #. If you mention also, it'll work.
For more reference

The file you're attempting to import is a GitHub viewer for a file. To import the raw data for that file, you'd want to use this code:
<script>
const source = 'https://raw.githubusercontent.com/McJoe21/coderslib/master/index.js';
fetch(source).then((response) => {
return response.text()
}).then((response) => {
eval(response);
}).catch((error) => {
console.error(`An error occured while attempting to load the "${source}" resource!`);
console.error(error);
});
</script>
Since GitHub does not directly allow the import of their user content, you will need to wrap your source URL in the above fetch-eval block.

Related

Read a JSON gist as a query string

I currently have a Javascript application that consists of three files:
index.html
app.js
input.json
The input.json file gets referenced several times by the app.js file, in order to render content into divs in the index.html file.
I want to make it so that loading my index.html at http://example.com/myapp can take an externall hosted JSON as the source for app.js to read, like myexample.com/myapp?myhost.com/files/input.json.
Can anybody advise me on how to get this working?
For this to work, you need to enable CORS on myexample.com.
Assuming you are using jQuery. (Take a look at here if you don't want to use jQuery for ajax requests)
$.get('http://myexample.com/myapp?myhost.com/files/input.json')
.done(function(data) {
// use external 'data' here.
})
.fail(function() {
// handle error here
});

cannot find js file

I have stucture code like this:
I try to load javascript into php file like this:
But i have an error like this:
This is my html :
And this is another javascript:
And i try to copy paste the link, and i got an error 404 not found. How can i fix it? Thanks.
Permissions
When the host is correct, and the file is in the right place, and you have no other networking problems, you may sometimes still get a 404 because of bad file permissions. If a server does not have permission to access a file, it may send out a 404 error in response. The reason why some "Not Authorized" error is not given instead, is that this would reveal more information about the files than you, the owner of the server, may intend. The way to respond to requests for privileged files without revealing whether or not they exist is to give a 404.
On Windows, you can view and change the permissions from the File Explorer by right-clicking on the file or folder, then going to Properties -> Security -> Edit. For more information, see the notes on permissions on Microsoft's site.
File Types
Besides permissions, a server must also be configured to serve the type of file you are accessing. If files with different extensions are served, but .js files are not, check the configuration of your server to make sure that .js files aren't blacklisted (or not whitelisted, as the case may be).
Directory Location
You should also verify that the files are actually stored in the top-most directory of the web server if that's how you are accessing them. If they aren't, you may need to prefix the path with the path from the webserver root to your application directory. E.g., instead of fusioncharts/..., you may need /path/to/fusioncharts/... or ../../path/to/fusioncharts.
Other Considerations
In your particular case, you should also verify that the files inside the fusioncharts folder are actually structured the way you think. (E.g., is there really a js/[insert name here].js file inside the fusioncharts folder?
If none of that solves your problem, try to take something that is working and gradually make it more and more similar to the files that aren't working. By figuring out at which point you go from a working setup to a not working setup, you may discover the problem.
If you are referring to a file with path: /ui/new-file.js
then,
1.In html file include
<script type="text/javascript" src="/ui/new-file.js"></script>
2.In server.js or app.js whichever you have, include
app.get('/ui/new-file.js', function (req, res) {
res.sendFile(path.join(__dirname, 'ui', 'login-file.js'));
});
Assuming you are using codeigniter, you can use base_url() function to include JS files in your codeignitor view template file.
<script src="<?php echo base_url(); ?>fusioncharts/js/fusioncharts.js" type="text/javascript"></script>
codeigniter default view template is called welcome_message.php and this file is located in application/view folder.
This is how I include js files in my codeigniter projects. Hope this will help.
In the html you can write *script** in the head or in the body, but not in your file js, delete this in fusionCharts.js
<script type=text/javascript>
In fusionCharts.js write only the function without the script
If you are developing locally, try clearing your cache.
Google Chrome likes to use the cached JavaScript files instead of the real ones.
Clearing your cache should resolve the issue.

include() like function in javascript

objective
I need a function that simply takes all the code from another file and pastes the code in the calling file.
possible solution
a function that works like the include() function in PHP.
reason
When I had hosting, I used the php function include("filename.html") to include things like headers and footers, in all the files on the website. This made life a lot easier!
Now I don't have hosting, because I am working on another site, and I am using Github Pages and thus, I can't use PHP. I need to use only HTML, JS and jQuery etc. So, I need a function that simply takes all the code from another file and pastes the code in the calling file.
Already tried
load() in jQuery.
<pre><script>
$(document).ready(function(){
$("#topbar").load("menubar.html");
});
</script></pre>
This question. I tried the accepted answer, but that didn't work for me.
Kindly help me with this issue.
You should consider setting up a build environment where you can compile your content locally before publishing it. This way, you can organize your code in different files (like in your case, with a header/footer that will always be included with different content files), compile locally to have the files automatically combined into a publish directory, and upload that instead.
This way, instead of e.g. sending 3 requests for a header, content and footer file, the header and footer are pre-compiled into the content file which can then be served with 1 request.
Personally I use Grunt as a build tool for purely static sites, together with a concatenation task (such as grunt-contrib-concat). There are several tutorials on the Grunt website, but you can see an example of how to configure a task for your specific problem here:
https://stackoverflow.com/a/12749861/351435
I do something like that :
var template = {
get: function (url, callback) {
if (this[url]) return callback(null, this[url]);
var self = this;
$.ajax({
"url": url,
"type": "GET"
})
done(function (html) {
self[url] = html;
callback(null, html);
})
.fail(callback);
}
};
after you just need to do that :
template.get("/menu.html", function (err, html, reason) {
if (err) return alert('An error is append : '+reason);
$("#topbar").html(html) // or append
});
I am assuming your scripts run in a browser.
Try the $.getScript function in jQuery.
`$.getMyScript("script.js", function(){
alert("Script executed.");
});`
Depending on how complex you want your solution to get, you could also look at http://requirejs.org/ for incorporating files/scripts/modules.
I believe this question is answered in full on How do I include a JavaScript file in another JavaScript file?.

javascript file not loading

Trying to import my js file from my page.
My page is in webcontent/mydomain/templates/page.xhtml
My js is in webcontent/mydomain/test/scripts
In page.xhtml
<script type="text/javascript" src="../test/scripts/test.js"></script>
But still the script is not getting picked.
Can anyone tell how I need to give the path in src.
Try this:
<script src="/test/scripts/test.js"></script>
Provided that webcontent is the root of public web content and thus /mydomain is also a public folder and thus your JavaScript is standalone available by http://localhost:8080/context/mydomain/test/scripts/test.js, assuming a domain of http://localhost:8080 and a context path of /context, then the following should do:
<script src="#{request.contextPath}/mydomain/test/scripts/test.js"></script>
This will generate a domain-relative URL with a dynamically inlined context path, which is much more robust than fiddling with ../ which would make the URI relative to the current request URI (as you see in browser's address bar) and not to the physical location of the template file as many starters incorrectly assume.

Calling external .js from ASP.NET MVC

I'm JavaScript newbie. What I'd like to be able to do is to call a function from .js file sitting in ASP.NET MVC project's scripts folder.
The function is:
function myfunction() {
alert("HELLO");
}
...and it resides in file brfix.js
On a viewpage I call it like this:
<script src="../../Scripts/brfix.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
myfuntion();
});
</script>
But the code doesn't work. However, if I place js-code directly onto the viewpage, it works, like this:
<script type="text/javascript">
$(document).ready(function() {
alert("HELLO");
});
</script>
How to call a file-based js function? Could some JavaScript-Big-Kahuna help me out? =)
If that code is pasted directly from your source code, you have a typo so that'd be why it doesn't work!
your function is called myfunction(), but you're calling myfuntion()
you should enable js errors in your browser when developing. You don't say which browser you're using. For IE it's in Tools - Options - Advanced. Uncheck the "disable script debugging" options. In firefox I'd use something like FireBug as Dror says, if memory serves there are things that appear in the event of a javascript error. If you are still having problems I would try installing Fiddler2 (in IE) and building a request for the js file and see what comes back.
Another option would be to put a debugger; call just before you call your function, you should then be able to step through the javascript.
It may be that the reference to the external file is wrong:
<script src="../../Scripts/brfix.js" type="text/javascript"></script>
Make sure the reference is correct.
You can try by using view source to see the actual location ../../Scripts/brfix.js gets translated to in the final page.
You can also try with FireBug of FireFox.
If your mvc site is the root site in iis you can start the script src with a slash to get to the scripts. otherwise you can use an asp:ScriptManager to include the scripts
As other posters have mentioned, there is a typo. However...
Check out the Url.Content() method for referencing your site content. (images, scripts, etc...) Using ../.. isn't reliable, especially if you have varying levels of depth in your URLs or your application lives in a subdirectory.
Here's a helper I use in most of my projects, for example:
public static string Script(this HtmlHelper Html, string url)
{
UrlHelper Url = new UrlHelper(new RequestContext(Html.ViewContext.HttpContext, Html.ViewContext.RouteData));
string html = "<script type=\"text/javascript\" src=\"{0}\"></script>";
return string.Format(html, Url.Content(url));
}
And here it is being called:
<%= Html.Script("~/public/js/blah.js") %>
I had the same problem and it turned out that I had a few js files that weren't being found. If your MVC project structure is the default VS setup and your View page is in Home for example, then I think below will find the file:
<script src="../Scripts/brfix.js" type="text/javascript"></script>
But even if that one is found other js files not being found caused my $(document).ready not to work. Check your page in Firefox's Firebug, if a file isn't found you will see html markup with a message saying a resource could not be found, located underneath the offending reference. Once I resolved all the js references then my $(document).ready worked.
Strangely VS was telling me it couldn't find the js files when the references were correct, and wasn't flagging the problem when the references were incorrect.

Categories

Resources