我有一些特定于排序表的代码。由于代码在大多数页面中都很常见,因此我想创建一个JS文件,其中将包含代码,并且所有使用它的页面都可以从那里引用它。
问题是:如何在.js文件中添加jQuery和表分类器插件?
我尝试了这样的东西:
document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></script>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></script>');但这似乎行不通。
做这件事最好的方法是什么?
发布于 2019-07-06 19:41:11
从js文件中动态添加jQuery,CSS。当我们将onload函数添加到body中时,我们可以使用jQuery从js文件创建页面。
init();
function init()
{
addJQuery();
addBodyAndOnLoadScript();
addCSS();
}
function addJQuery()
{
var head = document.getElementsByTagName( 'head' )[0];
var scriptjQuery = document.createElement( 'script' );
scriptjQuery.type = 'text/javascript';
scriptjQuery.id = 'jQuery'
scriptjQuery.src = 'https://code.jquery.com/jquery-3.4.1.min.js';
var script = document.getElementsByTagName( 'script' )[0];
head.insertBefore(scriptjQuery, script);
}
function addBodyAndOnLoadScript()
{
var body = document.createElement('body')
body.onload =
function()
{
onloadFunction();
};
}
function addCSS()
{
var head = document.getElementsByTagName( 'head' )[0];
var linkCss = document.createElement( 'link' );
linkCss.rel = 'stylesheet';
linkCss.href = 'E:/Temporary_files/temp_css.css';
head.appendChild( linkCss );
}
function onloadFunction()
{
var body = $( 'body' );
body.append('<strong>Hello world</strong>');
}html
{
background-color: #f5f5dc;
}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Temp Study HTML Page</title>
<script type="text/javascript" src="E:\Temporary_files\temp_script.js"></script>
</head>
<body></body>
</html>
https://stackoverflow.com/questions/1140402
复制相似问题